Exception Handling
⏱ 18 min read read
try / catch / finally:
try {
// risky code here
} catch (InvalidArgumentException $e) {
// handle specific exception
} catch (RuntimeException $e) {
// handle another type
} catch (Exception $e) {
// catch-all for any Exception
} finally {
// ALWAYS runs --- cleanup code here
}
Common Built-in Exceptions:
Exception --- base class for all exceptions
InvalidArgumentException --- bad argument value
OutOfRangeException --- index/offset out of valid range
RuntimeException --- error at runtime
LogicException --- errors in program logic
OverflowException --- container is full
UnderflowException --- container is empty
TypeError --- wrong type passed
ValueError --- right type, wrong value (PHP 8+)
DivisionByZeroError --- division or modulo by zero
Error --- base class for fatal errors (PHP 7+)
Throwable --- interface for both Error and Exception
Custom Exceptions:
class InsufficientFundsException extends RuntimeException {
public function \_\_construct(private float $shortfall) {
parent::\_\_construct(
"Insufficient funds. Need \${shortfall} more."
);
}
public function getShortfall(): float { return $this->shortfall; }
}
throw new InsufficientFundsException(4300.00);
PHP uses throw new ExceptionClass() --- not just throw new.
PHP 7+ introduced Error class for fatal errors (separate from
Exception).
Catch Throwable to catch BOTH Exception and Error.
PHP 8+ allows throw as an expression: $name = $input ?? throw new
Exception();
try {
// risky code here
} catch (InvalidArgumentException $e) {
// handle specific exception
} catch (RuntimeException $e) {
// handle another type
} catch (Exception $e) {
// catch-all for any Exception
} finally {
// ALWAYS runs --- cleanup code here
}
Common Built-in Exceptions:
Exception --- base class for all exceptions
InvalidArgumentException --- bad argument value
OutOfRangeException --- index/offset out of valid range
RuntimeException --- error at runtime
LogicException --- errors in program logic
OverflowException --- container is full
UnderflowException --- container is empty
TypeError --- wrong type passed
ValueError --- right type, wrong value (PHP 8+)
DivisionByZeroError --- division or modulo by zero
Error --- base class for fatal errors (PHP 7+)
Throwable --- interface for both Error and Exception
Custom Exceptions:
class InsufficientFundsException extends RuntimeException {
public function \_\_construct(private float $shortfall) {
parent::\_\_construct(
"Insufficient funds. Need \${shortfall} more."
);
}
public function getShortfall(): float { return $this->shortfall; }
}
throw new InsufficientFundsException(4300.00);
PHP uses throw new ExceptionClass() --- not just throw new.
PHP 7+ introduced Error class for fatal errors (separate from
Exception).
Catch Throwable to catch BOTH Exception and Error.
PHP 8+ allows throw as an expression: $name = $input ?? throw new
Exception();
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress