Thuta Learning
PHP
AdvancedProgrammingBeginner

Exceptions & Error Handling

PHPLesson 2635 min

What you'll walk away with

  • Use try, catch and finally and predict which block runs when
  • Explain the Throwable, Error and Exception hierarchy and why catch (Exception) does not catch a TypeError
  • Write custom exception classes and keep the original cause through the previous argument
  • Use set_error_handler and set_exception_handler to log details in one place and show a safe message in another

Explain it simply

Explain it simply

An exception is an object that PHP, or your own code, throws when something goes wrong. Throwing stops the normal flow and starts a search for a catch block that can handle it. Think of passing a phone call up the line until someone who can deal with it picks up.

The core idea of good error handling is to catch a failure only where someone, a person or the program, can actually recover from it. The details go to a log for developers, and the visitor sees a short, calm message.

Problem → Why → Solution

The problem: hiding errors inside return values

Without exceptions, a function that fails returns a magic value such as false, null or -1. The trouble is that every caller must remember to test it, and the moment one forgets, PHP carries on silently. Below, parsing 'abc' as an age fails, but false is then used in $age + 1, so the result is a plausible-looking 1 instead of an error.

magic-value.php
<?php
// A failure signalled by a magic return value
function parseAge(string $raw): int|false
{
    if (!ctype_digit($raw)) {
        return false;
    }
    return (int) $raw;
}

$age = parseAge('abc');
echo 'Next year you will be ', $age + 1;   // Next year you will be 1

Why exceptions are better

An exception cannot be ignored: if nobody catches it the script stops and the problem becomes visible. It also carries a message, a code, the file and line, and the call stack, which makes debugging far easier. The success path is no longer cluttered with if checks.

Core concept: try, catch, finally and Throwable

An exception is an object PHP throws when something goes wrong, and it travels up the call stack until a catch block handles it. If nothing does, the script ends with a fatal error. try wraps the code that might fail, catch (SomeType $e) handles one kind of failure, and finally runs whatever happens, which makes it the right place to release resources such as a file handle or an open transaction.

Everything throwable implements the Throwable interface, which has two branches. Error covers problems with the code or the engine itself: TypeError, ValueError, ArgumentCountError, DivisionByZeroError. Exception covers problems a program can reasonably anticipate at runtime: InvalidArgumentException, RuntimeException, JsonException, and PDOException from the database lessons. The important consequence is that catch (Exception $e) does not catch a TypeError, because TypeError is an Error. Catch Throwable only at the outermost boundary, where you want to log anything and show a safe page.

Pick the exception class to say who is at fault. LogicException and its children (InvalidArgumentException) mean the caller used the function wrongly, while RuntimeException means something went wrong at runtime even though the call was valid, such as a missing file or a failed query. Define your own class when callers need to react differently, for example InsufficientFundsException, and keep it tiny: final class X extends RuntimeException {}.

Not every problem is an exception. Warnings, notices and deprecations are an older mechanism: PHP prints or logs them and carries on, so reading an undefined array key does not stop the script. You can promote them to exceptions with set_error_handler() and ErrorException, and many frameworks do exactly that. A few failures, such as running out of memory, are fatal and cannot be caught at all, which is why the final safety net matters: set_exception_handler() registers a function for any exception nobody caught, and it should log the details and show only a generic message.

Mental model: a problem travelling up the stack
  1. throw creates the exception object
  2. PHP unwinds the call stack upward
  3. First matching catch handles it
  4. finally runs, then execution resumes

If no catch matches all the way up, the script dies with a fatal error.

General pattern

pattern.php
<?php
try {
    riskyCall();
} catch (SpecificException $e) {
    // recover, or translate it and rethrow
} catch (Throwable $e) {
    // last resort: log it
} finally {
    // always runs: release resources
}

When code in the try block throws, the first matching catch runs, so put specific types first and the broad Throwable last. finally runs whether or not an exception occurred, and even when the block returns.

Example: a divide() that refuses a zero divisor

The example divides two numbers but refuses a zero divisor with an InvalidArgumentException. As written it takes the happy path and prints 5; change divide(10, 2) to divide(10, 0) and the catch block runs instead, sending the real message to the error log and showing the visitor only a calm sentence. Keeping a detailed log apart from a vague public message is the habit this lesson is built around.

On the command line error_log() writes to stderr; on a web server it goes to the configured error log.

php
<?php
declare(strict_types=1);
function divide(float $a, float $b): float {
    if ($b == 0.0) throw new InvalidArgumentException('zero divisor');
    return $a / $b;
}
try { echo divide(10, 2); } catch (InvalidArgumentException $e) {
    error_log($e->getMessage()); echo 'Invalid calculation';
}

Code breakdown

  1. Line 2declare(strict_types=1);

    Turns strict types on. Passing the int 10 to a float parameter is still allowed in strict mode (it is a widening conversion), but passing the string '10' would raise a TypeError.

  2. Line 4if ($b == 0.0) throw new InvalidArgumentException('zero divisor');

    A guard clause. If the caller passed a bad argument, the function stops at once and throws an exception object. InvalidArgumentException fits because the mistake is the caller's.

  3. Line 5return $a / $b;

    This line is reached only after the guard passed, so $b is known to be non-zero. 10 / 2 is the float 5.0, which echo prints as 5.

  4. Line 7try { echo divide(10, 2); } catch (InvalidArgumentException $e) {

    The protected region. Nothing is thrown this time, so the catch is skipped. The catch handles only InvalidArgumentException (and its subclasses); other types keep travelling upward.

  5. Line 8error_log($e->getMessage()); echo 'Invalid calculation';

    The developer detail ('zero divisor') goes to the log while the visitor sees only a generic message. This split matters in production; try this branch with divide(10, 0).

You should see
5

The Throwable family tree

Knowing where a class descends from lets you predict what a catch clause will match. This code prints each class's parent chain with class_parents(), and you can compare it with the picture below. catch (RuntimeException $e) catches a PDOException because PDOException is a child of RuntimeException.

hierarchy.php
<?php
$classes = [
    InvalidArgumentException::class,
    PDOException::class,
    JsonException::class,
    ArgumentCountError::class,
    ValueError::class,
    DivisionByZeroError::class,
];

foreach ($classes as $class) {
    $chain = [$class, ...array_values(class_parents($class))];
    echo implode(' > ', $chain), "\n";
}

var_dump(new TypeError() instanceof Throwable);
var_dump(new TypeError() instanceof Exception);
text
Throwable family tree (simplified)
----------------------------------
Throwable (interface)
|-- Error                    problems in the code or the engine
|   |-- TypeError
|   |   +-- ArgumentCountError
|   |-- ValueError
|   +-- ArithmeticError
|       +-- DivisionByZeroError
+-- Exception                problems a program can anticipate
    |-- LogicException
    |   +-- InvalidArgumentException
    |-- RuntimeException
    |   +-- PDOException
    +-- JsonException

The picture is simplified; the real tree has more classes. The two var_dump lines confirm that a TypeError is a Throwable but not an Exception.

Catch order, several types and finally

PHP checks the catch blocks from top to bottom and runs only the first match, so put the specific types first. catch (A | B $e) handles two unrelated types in one block. In the code below the 'type' case calls strlen([]), which raises a TypeError, skips the first catch and lands in the Throwable catch. Note that finally runs on all four iterations.

catch-order.php
<?php
function risky(string $kind): string
{
    return match ($kind) {
        'argument' => throw new InvalidArgumentException('bad argument'),
        'runtime' => throw new RuntimeException('bad runtime state'),
        'type' => (string) strlen([]),
        default => 'fine',
    };
}

foreach (['fine', 'argument', 'runtime', 'type'] as $kind) {
    try {
        echo risky($kind), "\n";
    } catch (InvalidArgumentException | RuntimeException $e) {
        echo 'Exception: ', $e->getMessage(), "\n";
    } catch (Throwable $e) {
        echo get_class($e), ': ', $e->getMessage(), "\n";
    } finally {
        echo "  (finished $kind)\n";
    }
}

Custom exceptions and chaining with previous

When you catch a low-level exception and throw a higher-level one, pass the original as the third constructor argument ($previous). getPrevious() then lets you walk the chain, and the log shows the root problem. Callers understand ConfigException at once, 'the config could not be read', without knowing anything about the JSON parser. The JSON_THROW_ON_ERROR flag makes json_decode() throw a JsonException instead of returning null.

chained.php
<?php
final 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);
    }

    if (!isset($data['db_host'])) {
        throw new ConfigException('Missing key: db_host');
    }
    return $data;
}

foreach (['{"db_host":"localhost"}', '{oops', '{}'] as $input) {
    try {
        $config = loadConfig($input);
        echo 'Loaded host ', $config['db_host'], "\n";
    } catch (ConfigException $e) {
        echo get_class($e), ': ', $e->getMessage(), "\n";
        $cause = $e->getPrevious();
        while ($cause !== null) {
            echo '  caused by ', get_class($cause), ': ', $cause->getMessage(), "\n";
            $cause = $cause->getPrevious();
        }
    }
}

Errors, warnings and the last-resort handler

The first code shows PHP 8 engine errors: a string under strict types raises a TypeError, dividing or taking a remainder with 0 raises a DivisionByZeroError, and fdiv() returns INF without throwing. It then converts an undefined array key warning into an ErrorException with set_error_handler() so it can be caught. Without that handler the warning would be printed and the script would carry on.

errors.php
<?php
declare(strict_types=1);

function half(int $n): int
{
    return intdiv($n, 2);
}

try {
    half('10');
} catch (TypeError $e) {
    $message = explode(', called in', $e->getMessage())[0];
    echo 'TypeError: ', $message, "\n";
}

$zero = 0;
try {
    echo 10 % $zero;
} catch (DivisionByZeroError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    echo 10 / $zero;
} catch (DivisionByZeroError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

echo 'fdiv: ', fdiv(1, 0), "\n";

// A warning is not an exception, unless you convert it
set_error_handler(function (int $severity, string $message, string $file, int $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
});

$prices = ['apple' => 100];
try {
    echo $prices['mango'];
} catch (ErrorException $e) {
    echo 'Converted warning: ', $e->getMessage(), "\n";
}
restore_error_handler();

The second code is the final safety net. The function registered with set_exception_handler() runs for any exception nobody caught, and then the script ends, so 'never printed' is never seen. The handler logs the real message (here text that mentions a password) and shows the visitor only a generic sentence. In production, setting display_errors to Off and log_errors to On in php.ini keeps stack traces away from visitors.

last-resort.php
<?php
set_exception_handler(function (Throwable $e): void {
    // Real details go to the log, never to the visitor
    error_log(sprintf('Uncaught %s: %s', $e::class, $e->getMessage()));
    echo "Something went wrong. Please try again later.\n";
});

echo "Starting\n";
throw new RuntimeException('database password is hunter2');
echo "never printed\n";

In real projects

Where this shows up in real projects

Frameworks centralise all of this. Laravel's exception handler and Symfony's kernel.exception event map exception types to HTTP responses (404, 422, 500) while log channels receive the details. Libraries throw their own types so you can catch precisely: PDOException from the database, JsonException from json_decode with JSON_THROW_ON_ERROR, request exceptions from HTTP clients. A well-built service layer translates these into domain exceptions such as OrderNotFound, so a controller never needs to know whether the data came from MySQL or an API.

In production, set display_errors to Off and log_errors to On, because a stack trace can contain file paths and sometimes even function arguments. Showing the visitor a short reference number and letting support look it up in the log is a safe and useful pattern.

Common mistakes

Common mistakes

1. Swallowing an exception with an empty catch

Writing catch (Exception $e) {} does not remove the bug, it only hides it. Every catch should recover, log or rethrow; if it does none of those, you do not need the catch.

2. Putting a broad catch before a specific one

With catch (Exception $e) placed before catch (InvalidArgumentException $e), the first block always catches the InvalidArgumentException, so the second never runs. PHP does not warn you about it. Keep specific types on top and broad ones below.

3. Expecting catch (Exception) to catch a TypeError

A TypeError is an Error, not an Exception, so when strlen([]) fails inside a try, a catch (Exception $e) is skipped and the error escapes. Use catch (Error $e) or Throwable when you also want engine errors, but keep that at the outermost boundary.

4. Losing the cause when you rethrow

throw new RuntimeException($e->getMessage()); drops the original class, line and stack trace. Pass $e as the third argument: throw new RuntimeException('Could not load config', 0, $e);

5. Showing the exception message to visitors

echo $e->getMessage(); can reveal a database host, a table name and sometimes credential details. Keep the detail in the log and give the visitor a generic message and a reference number.

Best practices

Best practices

  • Catch only where you can recover or translate meaningfully; let everything else travel upward.
  • Translate low-level exceptions into your own domain classes (such as OrderNotFound) and always pass previous.
  • Put one set_exception_handler (or the framework's handler) at the entry point to log and show a generic response.
  • Do not use exceptions to steer normal flow; for something routine like 'no such user', returning null may fit better.

Mini challenge

Mini challenge: a validator that explains why

Write a function that validates age strings coming from a form. When one is wrong it throws a custom exception that carries the reason, and a loop catches each failure and counts every checked input in finally.

  • final class InvalidAgeException extends InvalidArgumentException with a promoted public readonly string input and a message built in the constructor
  • parseAge(string $raw): int trims, validates with filter_var(..., FILTER_VALIDATE_INT) and throws for 'not a whole number' and 'outside 0-150'
  • In the foreach loop catch InvalidAgeException only (not Exception) and bump the checked counter in finally
  • Finish by printing how many inputs were checked and which ages were valid
age-validator.php
<?php
declare(strict_types=1);

// TODO: final class InvalidAgeException extends InvalidArgumentException
//       with a promoted public readonly string $input; message built in the constructor

// TODO: function parseAge(string $raw): int
//       trim, check with filter_var(..., FILTER_VALIDATE_INT)
//       throw InvalidAgeException for "not a whole number" and for "outside 0-150"

$checked = 0;
$valid = [];

// TODO: loop over ['25', 'abc', '-3', '200', ' 41 ']
//       try:     parse, remember the age, print "'<raw>' accepted"
//       catch:   InvalidAgeException only; print its message
//       finally: count the input as checked

// TODO: print "Checked N inputs, valid ages: a, b"

Expected: '25' accepted 'abc' is not a valid age: not a whole number '-3' is not a valid age: outside 0-150 '200' is not a valid age: outside 0-150 ' 41 ' accepted Checked 5 inputs, valid ages: 25, 41

Show hint

filter_var returns false on failure but a valid 0 is also falsy, so compare with === false. In the custom exception's constructor call parent::__construct(...) with the message.

Show solution
age-validator.php
<?php
declare(strict_types=1);

final class InvalidAgeException extends InvalidArgumentException
{
    public function __construct(public readonly string $input, string $reason)
    {
        parent::__construct("'$input' is not a valid age: $reason");
    }
}

function parseAge(string $raw): int
{
    $age = filter_var(trim($raw), FILTER_VALIDATE_INT);
    if ($age === false) {
        throw new InvalidAgeException($raw, 'not a whole number');
    }
    if ($age < 0 || $age > 150) {
        throw new InvalidAgeException($raw, 'outside 0-150');
    }
    return $age;
}

$checked = 0;
$valid = [];

foreach (['25', 'abc', '-3', '200', ' 41 '] as $raw) {
    try {
        $valid[] = parseAge($raw);
        echo "'$raw' accepted\n";
    } catch (InvalidAgeException $e) {
        echo $e->getMessage(), "\n";
    } finally {
        $checked++;
    }
}

echo "Checked $checked inputs, valid ages: ", implode(', ', $valid), "\n";

Quick quiz 1 / 3

A TypeError is thrown inside a try block. Which catch clause can handle it?

Quick quiz 2 / 3

What does echo f(); print for function f() { try { return 'try'; } finally { echo 'finally '; } }?

Quick quiz 3 / 3

When wrapping a low-level exception in your own, why pass the original as the third argument ($previous)?

What to remember

  • When code in try throws, the first matching catch runs and finally always runs; put specific types first.
  • Throwable has two branches, Error (engine and code problems) and Exception (runtime problems), so catch (Exception) does not catch a TypeError.
  • Keep custom exceptions tiny and always pass previous when translating a low-level exception.
  • Warnings are not exceptions (set_error_handler can convert them), set_exception_handler is the last boundary; show visitors a generic message and keep the detail in the log.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.