Error Handling — PHP

An exception is an object that carries the news that something failed. throw new SomeException("message") stops the function and throws that exception. try {…

A customer orders an Iced Tea that is out of stock, and the whole order page turns into PHP Fatal error: Uncaught .... The program only needed to say "Sorry, the Iced Tea is gone", and then continue serving.

Error handling is how your program reacts when something fails, without stopping itself. Picture Mrs. Tini's Stall on a busy day. A waiter writes down "Iced Tea, 2 glasses", then notices there is none left. He doesn't freeze: he throws the news to the front. The cashier, who is ready to catch it, tells the customer "Sorry, the Iced Tea is gone". If nobody catches it, the stall closes without warning. And whatever happens, the receipt still gets closed.

In PHP that news is called an exception: an object that carries a message about what failed. The code that finds the problem throws it with throw, like the waiter. Other code catches it with try/catch, like the cashier. The stall closing without warning is the program stopping with a Fatal error. The receipt that still gets closed is finally, which runs whatever happens.

throw: throwing a problem

This is order.php, the order taker of Mrs. Tini's Stall. The function order checks the quantity and the stock, and throws an exception when something is wrong:

<?php
class OutOfStockException extends RuntimeException {}

function order(string $menu, int $quantity): string {
    $stock = ["Fried Rice" => 3, "Iced Tea" => 0];
    if ($quantity < 1) {
        throw new InvalidArgumentException("Quantity must be at least 1, not $quantity");
    }
    if ($stock[$menu] < $quantity) {
        throw new OutOfStockException("$menu is out of stock");
    }
    return "$quantity $menu recorded";
}

echo "Start\n";
echo order("Iced Tea", 2) . "\n";
echo "Done\n";

Nothing catches the exception, so PHP stops and writes:

$ php order.php
Start
PHP Fatal error:  Uncaught OutOfStockException: Iced Tea is out of stock in /app/order.php:10
Stack trace:
#0 /app/order.php(16): order('Iced Tea', 2)
#1 {main}
  thrown in /app/order.php on line 10

How to read it:

The PHP Fatal error: prefix is the form of the message written to the log (the server's file of error notes) and to the terminal. When the setting display_errors is on, the same text also appears on the page as Fatal error: Uncaught ....

try and catch: catching it

Now the same call is wrapped in try and catch:

echo "Start\n";
try {
    echo order("Iced Tea", 2) . "\n";
    echo "Next\n";
} catch (OutOfStockException $e) {
    echo "Sorry: " . $e->getMessage() . "\n";
} finally {
    echo "Receipt closed\n";
}
echo "Done\n";

The result:

Start
Sorry: Iced Tea is out of stock
Receipt closed
Done

The order of try, catch, finally

Guess first: what does try { throw new Exception("Failed"); echo "A"; } catch (Exception $e) { echo "B"; } finally { echo "C"; } print?

The answer to the guess: throw jumps straight to catch, so echo "A" is skipped. catch prints B, then finally prints C. The output is BC.

A try must have at least one catch or a finally. With neither, PHP refuses the file before a single line runs: PHP Fatal error: Cannot use try without catch or finally.

Exception and Error: the two branches of Throwable

Everything that can be thrown implements the Throwable interface (a list of methods that a class must have, from the Advanced OOP lesson). The tree below shows its two branches. A class indented below another class is its child:

Throwable
├── Exception: problems you expect (bad input, out of stock)
│   ├── LogicException
│   │   └── InvalidArgumentException
│   └── RuntimeException
│       └── OutOfStockException (our own)
└── Error: mistakes PHP itself throws
    ├── TypeError
    ├── ValueError
    └── ArithmeticError
        └── DivisionByZeroError

catch catches the class it names and every class below it: its children, their children, and so on. So catch (Exception $e) catches out of stock (OutOfStockException) and a zero quantity (InvalidArgumentException). But the Error branch is not caught.

Take order("Fried Rice", "two"). "two" is not a number for int $quantity (a parameter type, from the Functions lesson), so PHP throws a TypeError. In this code, that TypeError gets past catch (Exception $e), and the catch (Throwable $e) below it catches it:

try {
    echo order("Fried Rice", "two") . "\n";
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage() . "\n";
} catch (Throwable $e) {
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}

get_class($e) returns the name of the exception's class, so the result is:

TypeError: order(): Argument #2 ($quantity) must be of type int, string given, called in /app/order.php on line 16

PHP checks the catch blocks one by one, from the top, and uses the first one that matches. So write the most specific catch (the class lowest in the tree) first.

Dividing by zero throws an Error too: in PHP 8, 30 / 0 throws DivisionByZeroError: Division by zero. That's why a function that divides usually checks the divisor first, and throws an InvalidArgumentException with a clear message when the divisor is zero. In the exercise you write a function like that: its message is Cannot divide by zero, and a division by any other number still returns its result, for example 10 / 2 gives 5.

Your own exceptions

class OutOfStockException extends RuntimeException {}

One line is enough. This class inherits everything from RuntimeException, the message and getMessage() included. The point is the name: catch (OutOfStockException $e) only catches out of stock, not other problems. End the name with Exception. Make it a child of RuntimeException (a problem that appears while the program runs) or LogicException (code used the wrong way).

💡 Rethrowing with previous

Sometimes you catch one exception, then throw another, clearer one for the code that called your function. Keep the old exception in the argument previous, so the original cause is not lost:

class OrderFailedException extends Exception {}

try {
    order("Iced Tea", 2);
} catch (OutOfStockException $e) {
    throw new OrderFailedException("Order for table 4 failed", previous: $e);
}
PHP Fatal error:  Uncaught OutOfStockException: Iced Tea is out of stock in /app/order.php:10
Stack trace:
#0 /app/order.php(18): order('Iced Tea', 2)
#1 {main}

Next OrderFailedException: Order for table 4 failed in /app/order.php:20
Stack trace:
#0 {main}
  thrown in /app/order.php on line 20

PHP prints both exceptions, starting from the first cause, OutOfStockException. After Next comes the exception that wraps it, OrderFailedException. If that OrderFailedException is caught, $e->getPrevious()->getMessage() inside its catch reads the original message.

💡 A warning is not an exception

order("Soup", 1) reads $stock["Soup"], but the key "Soup" is not in $stock. PHP only gives a warning:

PHP Warning:  Undefined array key "Soup" in /app/order.php on line 9

PHP prints the warning, then the program keeps running and reads $stock["Soup"] as null. A warning is not an exception, so try/catch cannot catch it. On line 9, $stock[$menu] < $quantity becomes null < 1, which is true. So the function throws an exception with the message Soup is out of stock. That message is misleading: soup is not on the menu at all. Check first with isset($stock[$menu]), then throw an exception with a correct message.

A warning can also be turned into an exception, so that it can be caught. On a real server, you usually add this once, at the start of the application, together with a final catcher for exceptions that no catch catches:

set_error_handler(fn($level, $message, $file, $line) =>
    throw new ErrorException($message, 0, $level, $file, $line));

set_exception_handler(function (Throwable $e) {
    error_log($e->getMessage());
    echo "Sorry, something went wrong. Try again later.\n";
});

try {
    order("Soup", 1);
} catch (ErrorException $e) {
    echo "Caught: " . $e->getMessage() . "\n";
}

echo order("Iced Tea", 2);
Caught: Undefined array key "Soup"
Sorry, something went wrong. Try again later.

⚠️ Problems that slip through or get swallowed

TL;DR: An exception is an object that carries the news that something failed. throw new SomeException("message") stops the function and throws that exception. try { ... } catch (Kind $e) { ... } catches it: the rest of try is skipped, catch runs, and $e->getMessage() reads the message. finally always runs, even before a Fatal error. Everything that can be thrown is a Throwable, with two branches: Exception (problems you expect) and Error (mistakes PHP itself throws, such as TypeError and DivisionByZeroError). catch (Exception $e) does not catch an Error. Your own exception only needs class XException extends RuntimeException {}, and the argument previous keeps the exception that was the original cause. An exception nobody catches ends with PHP Fatal error: Uncaught ... and a stack trace (the trail of function calls). A Warning is only a warning, not an exception: the program keeps running, and catch cannot catch it.

⚡ throw throws a problem

Write:

if ($quantity < 1) {
    throw new InvalidArgumentException("Quantity must be at least 1, not $quantity");
}

Meaning: An exception is an object that carries the news that something failed. throw new ... creates an exception object and throws it. Here, when $quantity (the number ordered) is less than 1, the function holding this code stops at the throw line. The code that catches the exception into the variable $e reads the message in the brackets with $e->getMessage(). If nobody catches it, PHP stops with PHP Fatal error: Uncaught ... (Uncaught: nobody caught it).

⚡ try and catch catch it

Write:

try {
    echo order("Iced Tea", 2) . "\n";
    echo "Next\n";
} catch (OutOfStockException $e) {
    echo "Sorry: " . $e->getMessage() . "\n";
} finally {
    echo "Receipt closed\n";
}

Meaning: try wraps code that might throw an exception. There is no Iced Tea left, so order("Iced Tea", 2) throws an OutOfStockException. As soon as something is thrown, the rest of the try is skipped, so "Next" is not printed. catch catches it and prints Sorry: Iced Tea is out of stock. finally always runs, and then the program continues as usual.

⚡ The order of try, catch, finally

Guess first: what does try { throw new Exception("Failed"); echo "A"; } catch (Exception $e) { echo "B"; } finally { echo "C"; } print?

BC. throw jumps straight to catch, so echo "A" is skipped. catch prints B, then finally prints C.

Meaning: When no catch matches the exception, finally still runs first, and then the program stops with a Fatal error.

⚡ catch (Exception) doesn't catch an Error

Meaning: Everything that can be thrown is a Throwable, with two branches: Exception and Error. TypeError (a value of the wrong type) and DivisionByZeroError (dividing by zero) are on the Error branch, not Exception, so both get past catch (Exception $e). Use Throwable when you really mean to catch everything. When there are several catch blocks, write the most specific one first, for example OutOfStockException before Exception.

What you will learn