PHP Exceptions
Things go wrong: a file is missing, a payment is declined, a user types "abc" where a number belongs. An exception is an object that signals such a problem. When code throws an exception, PHP stops running the current function and looks for a matching catch block further up. If nothing catches it, the script ends with a "Fatal error: Uncaught ..." message — something you never want users to see.
try, catch, finally
<?php
function divide(int $a, int $b): float
{
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide $a by zero");
}
return $a / $b;
}
try {
echo divide(10, 4) . PHP_EOL;
echo divide(3, 0) . PHP_EOL; // throws: the next line never runs
echo "not reached" . PHP_EOL;
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
} finally {
echo "finally always runs" . PHP_EOL;
}
echo "Script continues" . PHP_EOL;2.5
Error: Cannot divide 3 by zero
finally always runs
Script continues
| Block | When it runs |
|---|---|
try |
The code that might fail |
catch (Type $e) |
Only if an exception of that type (or a subclass) was thrown |
finally |
Always — after success, after a catch, even after a return |
The exception hierarchy
All exceptions and engine errors implement the Throwable interface. There are two branches: Exception for problems your code throws, and Error for mistakes PHP itself detects (calling an undefined function, a wrong argument type, dividing by zero with intdiv or %).
Throwable
├── Exception
│ ├── InvalidArgumentException, DomainException, LengthException, OutOfRangeException (LogicException family)
│ ├── RuntimeException, UnexpectedValueException, OutOfBoundsException … (RuntimeException family)
│ └── JsonException, PDOException, your own exception classes …
└── Error
├── TypeError
├── ValueError
├── ArithmeticError
│ └── DivisionByZeroError
└── …You can catch Errors too — useful for turning programmer mistakes into tidy messages:
<?php
function half(int $n): int
{
return intdiv($n, 2);
}
$attempts = [
fn() => half(9),
fn() => half("ten"), // TypeError
fn() => intdiv(1, 0), // DivisionByZeroError
fn() => str_repeat('x', -1), // ValueError
];
foreach ($attempts as $i => $try) {
try {
echo "#$i ok: " . $try() . PHP_EOL;
} catch (DivisionByZeroError $e) {
echo "#$i math: " . $e->getMessage() . PHP_EOL;
} catch (TypeError | ValueError $e) {
echo "#$i " . get_class($e) . PHP_EOL;
}
}#0 ok: 4
#1 TypeError
#2 math: Division by zero
#3 ValueError
Catch blocks are checked top to bottom, and TypeError | ValueError catches either type in one block. Put specific types before general ones like Exception or Throwable.
Custom exceptions
Create your own exception classes by extending Exception (or one of its subclasses). A meaningful class name lets callers react to exactly that problem, and extra properties can carry details:
<?php
class InsufficientFundsException extends RuntimeException
{
public function __construct(public readonly float $missing)
{
parent::__construct(sprintf('Balance too low: %.2f missing', $missing));
}
}
class Wallet
{
public function __construct(private float $balance) {}
public function pay(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException('Amount must be positive');
}
if ($amount > $this->balance) {
throw new InsufficientFundsException($amount - $this->balance);
}
$this->balance -= $amount;
echo "Paid $amount, left {$this->balance}" . PHP_EOL;
}
}
$w = new Wallet(50);
foreach ([20, -5, 45] as $amount) {
try {
$w->pay($amount);
} catch (InsufficientFundsException $e) {
echo $e->getMessage() . " (top up at least {$e->missing})" . PHP_EOL;
} catch (InvalidArgumentException $e) {
echo "Rejected: " . $e->getMessage() . PHP_EOL;
}
}Paid 20, left 30
Rejected: Amount must be positive
Balance too low: 15.00 missing (top up at least 15)
Rethrowing and chaining
Low-level code often catches a technical exception and throws a more meaningful one, passing the original as the previous exception so no information is lost:
<?php
class ConfigException extends Exception {}
function loadConfig(string $json): array
{
try {
return json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new ConfigException('Config file is broken', 500, $e);
}
}
try {
loadConfig('{"debug": true,}');
} catch (ConfigException $e) {
echo get_class($e) . ": " . $e->getMessage() . " (code " . $e->getCode() . ")" . PHP_EOL;
$prev = $e->getPrevious();
echo "Caused by " . get_class($prev) . ": " . $prev->getMessage() . PHP_EOL;
}ConfigException: Config file is broken (code 500)
Caused by JsonException: Syntax error
Useful methods on every exception: getMessage(), getCode(), getPrevious(), getFile(), getLine() and getTraceAsString(). Log the file, line and trace for developers, but show users only a friendly message.
Tip: On a real site, register a last-resort handler with
set_exception_handler()that logs the error and shows a generic "Something went wrong" page instead of a raw fatal error.
Test yourself
When does a finally block run?
- Only when no exception was thrown
- Only when an exception was caught
- Always, whether or not an exception occurred
- Only when the script ends
Which interface do both Exception and Error implement?
CatchableThrowableStringableFailure
How do you keep the original exception when throwing a new one?
- Pass it as the third constructor argument (
$previous) - Call
$e->rethrow() - Use
throw $e, $new; - It is lost automatically