PHP Tutorial · PHP for the Web · Lesson 28 of 38

PHP Exceptions

Throw and catch exceptions, use finally and create custom exception types.

try, catch, finally

Example 1Try it yourself
<?php
function divide(int $a, int $b): float
{
    if ($b === 0) {
        throw new InvalidArgumentException("Cannot divide by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 4), "\n";
    echo divide(1, 0), "\n";
} catch (InvalidArgumentException $e) {
    echo "Error: ", $e->getMessage(), "\n";
} finally {
    echo "finally always runs\n";
}
try {
    echo intdiv(1, 0);
} catch (DivisionByZeroError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

Output

2.5
Error: Cannot divide by zero
finally always runs
DivisionByZeroError: Division by zero

Custom exceptions

Extend Exception (or a more specific SPL class like InvalidArgumentException) so callers can catch exactly what they expect:

Example 2Try it yourself
<?php
class InsufficientFundsException extends RuntimeException
{
    public function __construct(public readonly float $shortBy)
    {
        parent::__construct(sprintf("Insufficient funds: short by %.2f", $shortBy));
    }
}

function withdraw(float $balance, float $amount): float
{
    if ($amount > $balance) {
        throw new InsufficientFundsException($amount - $balance);
    }
    return $balance - $amount;
}

try {
    withdraw(50, 80);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage(), " (", $e->shortBy, ")\n";
}

Output

Insufficient funds: short by 30.00 (30)

Errors are Throwable too

In PHP 7+, many fatal errors are thrown as Error objects (e.g. TypeError, DivisionByZeroError). Both Exception and Error implement Throwable.

Test yourself

Which interface do both Exception and Error implement?

  1. Catchable
  2. Throwable
  3. ErrorInterface
  4. Stringable
Show answer

Answer: Throwable