Learn/PHP/9. Handling errors
Lesson 9 of 15
Sign in

PHP, lesson 9

Handling errors

When something goes wrong at run time, modern PHP throws an object describing the problem. If nothing catches it, the script stops with a "Fatal error: Uncaught …" message. Catching lets your program recover, report the problem nicely, or try something else.

try and catch

When a statement inside try throws, PHP jumps straight to the first catch block whose type matches. The variable ($e) holds the thrown object; getMessage() returns its text. Since PHP 8 you can leave the variable out when you don't need it: catch (DivisionByZeroError).

Two families: Exception and Error

Everything you can throw implements the Throwable interface, which has two main branches:

  • : problems your program should expect and handle, like invalid input or a missing file. Its subclasses include , and .

2 exercises to try what you just read.

Exercise 1

Careful calculator

Press Ctrl Enter or Check to test your code.

Exercise 2

Piggy bank

Press Ctrl Enter or Check to test your code.

Exception
InvalidArgumentException
RuntimeException
LengthException
  • Error: usually a bug in the code, raised by PHP itself. Subclasses include TypeError (wrong argument type), ValueError (right type, impossible value), DivisionByZeroError and UnhandledMatchError.
  • catch (Exception $e) does not catch an Error, and vice versa. catch (Throwable $e) catches both, which is useful at the very top of a program but too broad elsewhere.

    Several catch blocks, multi-catch and finally

    The | lets one block handle several unrelated types. finally runs whether or not anything was thrown, so it's the place for clean-up code.

    Throwing exceptions

    When your own function gets something it can't handle, throw:

    Since PHP 8, throw is an expression, so it also works in places like ?? and arrow functions: $name = $input ?? throw new InvalidArgumentException("name required");.

    Your own exception classes

    Define a class that extends Exception (or one of its subclasses) when a failure belongs to your program's own rules. An empty body is enough; the class name carries the meaning:

    Callers can now catch exactly OutOfStockException and let anything unexpected through.

    Validating numbers

    Casting with (int) or (float) never fails, it silently gives 0 for garbage. To reject bad input, check it first with is_numeric(), which accepts strings like "42", "-3.5" and "1e3", and refuses "abc" or "".

    Warnings are not exceptions

    Some older functions report problems with a warning instead of throwing, for example reading a missing array key. Warnings print a message and carry on. Avoid them by checking first (isset(), ??), rather than trying to catch them.

    Further reading

    • The Exception class
    • try / catch
    • throw
    • The Error class hierarchy
    • Predefined exceptions

    Each input line holds two values separated by a space. Divide the first by the second and print the result with two decimals. Instead of crashing:

    • if either value is not numeric, print error: not a number
    • if the second value is zero, print error: division by zero

    Write divide(string $a, string $b): float, which throws an InvalidArgumentException for non-numeric input and lets PHP's own DivisionByZeroError happen for zero. Catch both in the loop.

    Sample input:

    Sample output:

    The first line is the starting balance (a whole number). Each following line is deposit N or withdraw N. Define InsufficientFundsException (extending RuntimeException) and make withdraw(int $balance, int $amount): int throw it when the amount is larger than the balance. When a withdrawal fails, print declined: balance is B and carry on. At the end print final: B.

    Sample input:

    Sample output:

    <?php
    
    try {
        $result = intdiv(10, 0);
        echo $result, "\n";          // skipped: the line above threw
    } catch (DivisionByZeroError $e) {
        echo "Oops: ", $e->getMessage(), "\n";   // Oops: Division by zero
    }
    echo "Still running\n";
    <?php
    
    try {
        $value = parse($input);
    } catch (InvalidArgumentException | LengthException $e) {
        echo "Bad input: ", $e->getMessage(), "\n";
    } catch (RuntimeException $e) {
        echo "Could not process\n";
    } finally {
        echo "Done\n";       // always runs, error or not
    }
    <?php
    
    function setVolume(int $level): int
    {
        if ($level < 0 || $level > 10) {
            throw new InvalidArgumentException("volume must be 0-10, got $level");
        }
        return $level;
    }
    <?php
    
    class OutOfStockException extends RuntimeException {}
    
    function take(int $stock, int $amount): int
    {
        if ($amount > $stock) {
            throw new OutOfStockException("only $stock left");
        }
        return $stock - $amount;
    }
    10 4
    7 0
    abc 2
    2.50
    error: division by zero
    error: not a number
    50
    withdraw 20
    withdraw 40
    deposit 15
    declined: balance is 30
    final: 45