Structured Exception Handling

Structured Exception Handling in PHP: --- A well-run factory line does not simply grind to a silent halt when something jams.


The Analogy: The Factory Emergency Stop and Incident Report

A well-run factory line does not simply grind to a silent halt when something jams. It has a system: the moment a machine detects a fault it cannot handle -- a part missing, a sensor out of range -- it pulls the emergency stop and raises a signal. That signal travels up the line looking for the first supervisor trained to deal with that specific kind of fault. A jam on the labeller is handled by the labeller's supervisor; a fault the labeller supervisor cannot handle keeps travelling up to the floor manager. An exception is that signal: thrown at the point a piece of code cannot proceed, it travels up the call stack until it reaches a handler equipped to deal with it.

The crucial discipline is that the signal is caught by the right level of supervisor, not just anyone. A minor labelling jam should be handled by the local supervisor who can clear it and resume; it should not shut down the entire plant. But a fault nobody recognises must not be quietly ignored either -- it travels all the way up to the floor manager, who at least logs it and stops the line safely rather than letting damaged product ship. Catching the specific fault you know how to handle, while letting the unknown propagate, is the whole art of catch blocks ordered from specific to general.

Every emergency stop also triggers a fixed shutdown routine that runs no matter what: gas valves close, guards lock, the incident is timestamped. This happens whether the fault was cleared locally or escalated to the manager -- it is unconditional cleanup. A finally block is that routine: code that runs whether the try succeeded, threw and was caught, or threw and propagated. It is where you release the resources -- the open file, the database connection -- that must be freed regardless of outcome.

The failure mode is the supervisor who catches every signal and throws it in the bin. A line where someone has wired the emergency stops to a switch that just resets everything and says nothing will run smoothly right up until it ships a thousand defective units, because every fault was silently swallowed. In code this is the empty catch (\Exception $e) {} that discards the error -- the single most damaging exception-handling mistake there is. A caught exception you do nothing about is worse than an uncaught one, because it hides the fault while letting the damage continue. Handle what you can, escalate what you cannot, and never, ever silently swallow.


Syntax or Core Structure

The core construct is try/catch/finally. Code that might fail goes in try; a matching catch handles a thrown exception; finally runs unconditionally afterwards. You raise an exception with throw.

<?php
declare(strict_types=1);

function divide(int $a, int $b): float {
    if ($b === 0) {
        throw new InvalidArgumentException('division by zero');
    }
    return $a / $b;
}

foreach ([[10, 2], [7, 0], [9, 3]] as [$a, $b]) {
    try {
        $r = divide($a, $b);
        echo "$a / $b = $r\n";
    } catch (InvalidArgumentException $e) {
        echo "$a / $b -> error: ", $e->getMessage(), "\n";
    } finally {
        echo "  (attempt done)\n";
    }
}

Output:

10 / 2 = 5
  (attempt done)
7 / 0 -> error: division by zero
  (attempt done)
9 / 3 = 3
  (attempt done)

The first and third divisions succeed and print their result. The middle one has a zero divisor, so divide throws InvalidArgumentException, the catch reports the message, and execution continues to the next iteration rather than crashing. Critically, the finally block runs after every case -- success or failure -- printing (attempt done) all three times. That unconditional run is what makes finally the right place for cleanup.


Technical Depth: The Hierarchy, Order, and Chaining

Throwable, Exception, and Error

PHP's throwable types form a hierarchy. Throwable is the root interface; below it sit Exception (for conditions your code raises and handles) and Error (for engine-level problems like type errors and division by zero). Catching Throwable catches both.

TypeRepresentsExample
ThrowableThe root of everything catchable--
ExceptionApplication-level conditionsRuntimeException, InvalidArgumentException
ErrorEngine-level faultsTypeError, DivisionByZeroError

Because catch matches the first compatible type, you order handlers from specific to general. A specific type placed after a general one is unreachable, since the general catch already claimed the exception.

<?php
declare(strict_types=1);

function parseAge(string $s): int {
    if (!ctype_digit($s)) {
        throw new InvalidArgumentException("not a number: $s");
    }
    $n = (int) $s;
    if ($n > 150) {
        throw new RangeException("implausible age: $n");
    }
    return $n;
}

foreach (['42', 'abc', '999'] as $s) {
    try {
        $age = parseAge($s);
        echo "ok: age = $age\n";
    } catch (RangeException $e) {
        echo 'range: ', $e->getMessage(), "\n";
    } catch (InvalidArgumentException $e) {
        echo 'invalid: ', $e->getMessage(), "\n";
    }
}

try {
    intdiv(1, 0);
} catch (\Throwable $e) {
    echo 'caught throwable: ', get_class($e), "\n";
}

Output:

ok: age = 42
invalid: not a number: abc
range: implausible age: 999
caught throwable: DivisionByZeroError

The valid 42 returns cleanly. The non-numeric abc throws InvalidArgumentException, caught by the second handler; 999 throws RangeException, caught by the first. The final block shows that intdiv(1, 0) raises a DivisionByZeroError -- an Error, not an Exception -- which is still a Throwable, so a Throwable catch reports its class. This is why catching only Exception can miss engine errors that Throwable would catch. Before PHP 7, engine faults were fatal errors you could not catch at all; the Throwable hierarchy is what made them catchable, which is why library code that must never crash on a caller's bad input often catches Throwable at its boundary rather than Exception.

Chaining to preserve the cause

When you catch a low-level exception and rethrow a higher-level one, pass the original as the third constructor argument. This "chains" the exceptions so the root cause is not lost.

<?php
declare(strict_types=1);

class ConfigException extends RuntimeException {}

function loadConfig(string $json): array {
    try {
        $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        throw new ConfigException('config is not valid JSON', 0, $e);
    }
    return $data;
}

try {
    loadConfig('{ broken');
} catch (ConfigException $e) {
    echo 'top: ', $e->getMessage(), "\n";
    echo 'cause: ', get_class($e->getPrevious()), "\n";
}

Output:

top: config is not valid JSON
cause: JsonException

json_decode with JSON_THROW_ON_ERROR raises a JsonException on bad input. The handler wraps it in a domain-specific ConfigException, passing the original as the third argument so getPrevious can retrieve it. The caller sees a meaningful high-level message -- "config is not valid JSON" -- while still being able to reach the underlying JsonException for logging. Chaining gives you a clean abstraction at the top without discarding the diagnostic detail underneath.

Catching several types at once

When two or more unrelated exception types warrant identical handling, a single catch can list them with the | union syntax, avoiding duplicated blocks.

<?php
declare(strict_types=1);

function toPositiveInt(string $s): int {
    if (!ctype_digit($s)) {
        throw new InvalidArgumentException("not digits: $s");
    }
    $n = (int) $s;
    if ($n === 0) {
        throw new DomainException('must be positive');
    }
    return $n;
}

foreach (['5', 'x', '0'] as $s) {
    try {
        $v = toPositiveInt($s);
        echo "value: $v\n";
    } catch (InvalidArgumentException | DomainException $e) {
        echo 'rejected (', get_class($e), ")\n";
    }
}

Output:

value: 5
rejected (InvalidArgumentException)
rejected (DomainException)

The value 5 passes. The non-digit x throws InvalidArgumentException and the zero throws DomainException, but the single union catch InvalidArgumentException | DomainException handles both identically, reporting the concrete class each time. Use this when the response is the same for several types; keep them in separate catches when each needs different handling.


Real World Example: Translating Failures into Clean Responses

A service layer should raise meaningful, typed exceptions and let the calling layer -- a controller -- translate each into the right response. Here UserService throws a NotFoundException or ValidationException, and the caller maps them to HTTP-style status codes, with a catch-all for anything unexpected.

<?php
declare(strict_types=1);

final class NotFoundException extends RuntimeException {}
final class ValidationException extends RuntimeException {}

final class UserService {
    private array $users = [1 => 'Ada', 2 => 'Ben'];

    public function rename(int $id, string $name): string {
        if (!isset($this->users[$id])) {
            throw new NotFoundException("no user $id");
        }
        if (trim($name) === '') {
            throw new ValidationException('name is empty');
        }
        $this->users[$id] = $name;
        return "renamed $id to $name";
    }
}

$svc = new UserService();

$attempts = [
    [1, 'Ada Lovelace'],
    [9, 'Ghost'],
    [2, '   '],
];

foreach ($attempts as [$id, $name]) {
    try {
        echo $svc->rename($id, $name), "\n";
    } catch (NotFoundException $e) {
        echo '404: ', $e->getMessage(), "\n";
    } catch (ValidationException $e) {
        echo '422: ', $e->getMessage(), "\n";
    } catch (\Throwable $e) {
        echo '500: unexpected', "\n";
    }
}

Output:

renamed 1 to Ada Lovelace
404: no user 9
422: name is empty

The first rename succeeds. The second targets a non-existent id, so NotFoundException is caught and mapped to 404. The third passes a blank name, raising ValidationException, mapped to 422. The final Throwable handler is a safety net for anything the service did not anticipate, mapping to a generic 500 without leaking internals. Typed exceptions let the service speak in domain terms while the boundary layer decides how each failure appears to the client.

The design flaw is that the catch-all Throwable handler prints a generic 500: unexpected and nothing else -- it does not log the actual error, so a genuinely unexpected fault leaves no diagnostic trail at all. In production this is dangerous: the day something truly unforeseen happens, the operator sees only "500: unexpected" with no message, no stack trace, and no exception class to investigate. The user-facing genericity is correct -- you must not leak internals to the client -- but that must be paired with detailed server-side logging of the caught throwable, its message, and its chained cause. As written, the code has conflated "hide the detail from the user" with "discard the detail entirely", which are opposite requirements: hide it from the response, but record it fully in the logs. A robust boundary handler logs the full exception (via error_log or a logger) at the moment of catching, then returns the sanitised message -- the next lesson on error handlers develops exactly this split between what the user sees and what the operator can debug.


Common Mistakes

  1. Silently swallowing exceptions. An empty catch (\Exception $e) {} hides faults while damage continues. Handle it, log it, or let it propagate -- never discard it.
  1. Catching too broadly too early. A top-level catch (\Throwable $e) around a small block hides bugs you should fix. Catch the specific type you can actually handle.
  1. Wrong catch order. Placing a general catch before a specific one makes the specific unreachable. Order handlers from most specific to most general.
  1. Using exceptions for normal control flow. Throwing to signal an ordinary, expected outcome is slow and obscures intent. Reserve exceptions for exceptional conditions.
  1. Losing the cause when rethrowing. Rethrowing without passing the original as previous discards the root cause. Chain exceptions so getPrevious can recover it.
  1. Only catching Exception, missing Error. Engine faults like TypeError are Error, not Exception. Catch Throwable when you truly need to handle everything.
  1. Leaking internals in the message shown to users. Exposing a raw exception message can reveal paths, queries, or secrets. Log the detail; show the user a sanitised message.
  1. Not cleaning up on failure. Forgetting to release a resource when an exception is thrown leaks it. Use finally for unconditional cleanup.
  1. Throwing strings or arrays. You can only throw Throwable instances. Throw a proper exception object with a clear type and message.

Best Practices

  • Catch only the exceptions you can meaningfully handle, and let the rest propagate to a layer that can.
  • Order catch blocks from specific to general, so each handler is reachable and the right one runs.
  • Use finally for cleanup that must happen regardless of success or failure, such as releasing resources.
  • Chain exceptions when wrapping a low-level cause in a domain exception, preserving the original via the third constructor argument.
  • Reserve exceptions for genuinely exceptional conditions, not for expected, routine outcomes.
  • Catch Throwable at trusted boundaries when you need to stop everything, but log the full detail before responding.
  • Show users a sanitised message while logging the complete exception, message, and chained cause server-side.
  • Define typed, domain-specific exceptions so callers can distinguish and translate different failures precisely.

Practice Exercises

  1. Write a divide function that throws on a zero divisor, and a loop that catches the exception and uses finally to print a cleanup line after every attempt.
  1. Create a parseAge function that throws InvalidArgumentException for non-numeric input and RangeException for implausible values, and catch each with correctly ordered handlers.
  1. Wrap a JsonException from json_decode in a custom ConfigException, chaining the cause, and print both the top message and the previous exception's class.
  1. Build a small service that throws typed NotFoundException and ValidationException, map each to a status code in the caller, add a Throwable safety net, and extend it to log the caught throwable before responding.