Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 147 ยท Errors and Exceptions

Exceptions

Learn PHP exceptions - throw, try/catch/finally, catching several types, catch without a variable, throw expressions and the Throwable, Error and Exception hierarchy.

An exception is an object that represents a failure. When code hits a problem it can't handle, it throws an exception; PHP then stops running the current code and jumps to the nearest place that has said "I can deal with this kind of problem", a catch block. If nothing catches it, the script ends with a fatal error.

Exceptions solve the big weakness of warnings: a warning lets the script carry on with a bad guess, while an exception refuses to continue until someone decides what to do. They also separate the normal path of your code from the error path, so you don't need to check a return value after every call. Modern PHP leans on them heavily: since PHP 8, type errors, division by zero, calls to undefined functions and invalid arguments to built-in functions all throw.

This lesson covers throw, try/catch/finally, catching several types, the built-in hierarchy and what an uncaught exception looks like. Custom Exceptions and Error Handling Strategy builds on it with your own exception classes and app-wide handlers.

Throwing and catching

You throw an exception with the throw keyword followed by an exception object. The built-in Exception class takes a message (and optionally a numeric code):

PHP
throw new InvalidArgumentException('Quantity must be at least 1');

To handle it, put the code that might fail in a try block and add a catch block for the type you expect:

PHP throw, try and catch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For quantity 0, the throw on line 7 ends orderTotal() immediately: the return never runs, and neither does the echo "Total..." line in the try block. PHP jumps straight to the matching catch, which receives the exception object as $e. After the catch block finishes, the loop continues normally with quantity 2, and the script reaches "All orders processed".

The key idea is that an exception travels up the call stack. The function that throws doesn't need to know who will handle the problem. orderTotal() just reports that the input is invalid; the loop decides that the right response is to print a message and move on.

What an exception object knows

Every exception carries information about where and why it was created:

Method Returns
getMessage() The message passed to the constructor
getCode() The integer code (0 if none was given)
getFile(), getLine() Where the exception was created (the new, not the catch)
getTrace(), getTraceAsString() The chain of function calls that led there
getPrevious() An earlier exception that caused this one (see chaining)

Echoing an exception object directly (it implements Stringable) prints the class, message, location and trace in one go, which is handy for logging.

What happens when nothing catches it

If an exception travels all the way up without meeting a matching catch, PHP prints a fatal error with a stack trace and stops. This example fails on purpose so you can read the output:

PHP An uncaught exception and its stack trace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call prints "Profile of Ada". The second ends the script with:

TEXT
Fatal error: Uncaught RuntimeException: Invalid user id -1 in main.php:5
Stack trace:
#0 main.php(12): loadUser(-1)
#1 main.php(17): showProfile(-1)
#2 {main}
  thrown in main.php on line 5

Read a stack trace from the top: the exception was thrown on line 5, inside loadUser(-1), which was called from line 12, inside showProfile(-1), which was called from line 17 in the main script (). The debugging lesson has more on reading traces.

On a production server, an uncaught exception with display_errors off shows the visitor a blank page or a generic "500 Internal Server Error". That's better than leaking a stack trace, but you should still catch exceptions at the top of your application and show a friendly error page. Custom Exceptions shows how with set_exception_handler().

finally: code that always runs

A finally block runs after the try (and any catch) no matter how the block ends: normally, through a caught exception, through an uncaught exception, or through a return. It's the place for cleanup such as closing files, releasing locks or ending a timer.

PHP finally always runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In both calls "Closing connection" prints before the returned value: PHP evaluates the return expression, runs finally, and only then leaves the function. The first call returns success, the second failed, and delta is never imported.

If a finally block contains its own return, that value replaces the one from try or catch, and it even swallows an uncaught exception. That's almost always a bug, so keep finally blocks to cleanup work and never return from them.

You can also write try with only finally and no catch. The exception then continues up the stack after the cleanup has run.

Catching several types

A try can have several catch blocks. PHP checks them in order and runs the first one whose type matches (the exception's class or any parent class or interface). So put specific types first and general ones last:

PHP
try {
    $data = fetchReport($id);
} catch (InvalidArgumentException $e) {
    // bad input: tell the user
} catch (RuntimeException $e) {
    // something failed while running: retry or log
} catch (Exception $e) {
    // anything else derived from Exception
}

If two types need the same handling, list them in one block separated by | (PHP 7.1+):

PHP Multiple catch types and the pipe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

'abc' and '200' land in the first block, which reports their class with $e::class. '9' throws a LogicException, which isn't listed in the first block, so it falls through to catch (Exception $e). Notice that the function is called before the echo. If you wrote echo 'Age accepted: ', parseAge($input);, PHP would print the first argument before calling the function, and "Age accepted:" would appear even for rejected input. RangeException is just a convenient built-in class; there's a full list of them below.

Catching without a variable (PHP 8.0)

When you don't need the exception object, you can leave out the variable:

PHP
try {
    $settings = loadSettings();
} catch (FileNotFoundException) {
    $settings = defaultSettings();
}

This makes it clear that ignoring the details is a deliberate choice.

The Throwable hierarchy

Everything that can be thrown implements the Throwable interface. Under it there are two separate families:

TEXT
Throwable (interface)
โ”œโ”€โ”€ Exception                  problems your code and libraries throw
โ”‚   โ”œโ”€โ”€ ErrorException         an old-style error turned into an exception
โ”‚   โ”œโ”€โ”€ JsonException          from json_encode/json_decode with JSON_THROW_ON_ERROR
โ”‚   โ”œโ”€โ”€ RuntimeException       failures detected while running
โ”‚   โ”‚   โ”œโ”€โ”€ OutOfBoundsException, OverflowException, RangeException,
โ”‚   โ”‚   โ””โ”€โ”€ UnderflowException, UnexpectedValueException
โ”‚   โ””โ”€โ”€ LogicException         mistakes in the program itself
โ”‚       โ”œโ”€โ”€ InvalidArgumentException, DomainException, LengthException,
โ”‚       โ””โ”€โ”€ OutOfRangeException, BadFunctionCallException โ†’ BadMethodCallException
โ””โ”€โ”€ Error                      problems PHP itself detects
    โ”œโ”€โ”€ TypeError โ†’ ArgumentCountError
    โ”œโ”€โ”€ ValueError             (PHP 8.0)
    โ”œโ”€โ”€ ArithmeticError โ†’ DivisionByZeroError
    โ”œโ”€โ”€ UnhandledMatchError    (PHP 8.0)
    โ””โ”€โ”€ AssertionError, CompileError โ†’ ParseError

The Exception branch is for conditions you expect might happen and plan for: bad input, a missing file, a failed network call. The SPL subclasses (InvalidArgumentException, RuntimeException and friends) give you ready-made names; pick the one that describes the problem rather than throwing a plain Exception.

The Error branch is for problems the engine detects, which usually mean a bug: calling a method on null, passing a string to an int parameter under strict types, dividing by zero. Error does not extend Exception, so catch (Exception $e) does not catch it. Only catch (Error $e) or catch (Throwable $e) will.

PHP Engine errors are Throwables too

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Every attempt skips the Exception block and lands in catch (Error $e):

  • 10 % 0 throws DivisionByZeroError: Modulo by zero. (Plain / by zero throws too, with the message "Division by zero".)
  • half('ten') throws a TypeError, because strict types forbid passing a string to an int parameter.
  • str_repeat('-', -3) throws a ValueError: since PHP 8, built-in functions throw instead of warning when an argument has the right type but an impossible value.
  • null->format('Y') throws Error: Call to a member function format() on null.
  • match with no matching arm throws UnhandledMatchError.

Don't wrap code in catch (Error $e) to hide bugs. A TypeError or "call to a member function on null" means the code is wrong and should be fixed. Catching Throwable belongs in one place: the top level of your application, where you log the problem and show an error page.

throw is an expression (PHP 8.0)

Since PHP 8.0, throw can be used anywhere an expression is allowed. That makes several short patterns possible:

PHP throw inside expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

?? falls back to a throw when the key is missing, a match arm throws for unexpected values, and an arrow function throws from a ternary. Before PHP 8, each of these needed a separate if statement. The output is Bookshop, bool(false), 5, and then Missing setting: DB_HOST from the catch block.

Exceptions vs return values

Not every failure deserves an exception. Use this rule of thumb:

  • Throw when the caller can't sensibly continue without handling the problem: invalid arguments, a database that's down, a file that must exist but doesn't, data that breaks a rule of your domain.
  • Return a value (like null, false or an empty array) when "nothing found" is a normal, expected answer: searching for a user who may not exist, looking up an optional setting.

For example, a findUser(int $id): ?User that returns null is fine, because callers will often expect "no such user". A getUser(int $id): User that promises a user should throw when there isn't one. Name your functions so the behavior is predictable.

Also avoid using exceptions for ordinary control flow, such as throwing to break out of a loop. They're slower than a break and they make the code harder to follow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside try { a(); b(); } catch (Exception $e) { c(); }, the call a() throws a RuntimeException. Which functions run?

    The throw ends the try block immediately, so b() never runs. RuntimeException extends Exception, so the catch block runs c().
  2. 2. A function returns 'ok' from its try block and its finally block echoes 'cleanup'. In what order do things happen?

    finally always runs, including after a return. PHP remembers the return value, runs finally, then leaves the function.
  3. 3. Under strict_types, a function with an int parameter is called with 'ten'. Which catch block catches it?

    PHP throws a TypeError, which is part of the Error family. Error does not extend Exception, so only catch (TypeError), catch (Error) or catch (Throwable) catch it.
  4. 4. Which statement is valid since PHP 8.0?

    throw became an expression in PHP 8.0, so it can follow ??. A catch always needs a type (only the variable is optional), you can only throw Throwable objects, and try needs at least one catch or finally.
  5. 5. A try has catch (Exception $e) first and catch (InvalidArgumentException $e) second. An InvalidArgumentException is thrown. What happens?

    PHP uses the first catch whose type matches, and an InvalidArgumentException is an Exception. Always put specific types before general ones.

Summary

  • throw new SomeException('message') stops the current code and sends the exception up the call stack to the nearest matching catch.
  • try { } catch (Type $e) { } handles it; the exception object offers getMessage(), getCode(), getFile(), getLine(), getTrace() and getPrevious().
  • An uncaught exception ends the script with Fatal error: Uncaught ... and a stack trace you read from the top down.
  • finally always runs, after try/catch and even after return; use it for cleanup and never return from it.
  • Several catch blocks are checked in order (specific first); catch (A | B $e) handles two types alike; PHP 8.0 lets you omit the variable.
  • Throwable has two families: Exception (expected failures; use SPL types like InvalidArgumentException and RuntimeException) and Error (engine-detected bugs: TypeError, ValueError, DivisionByZeroError, UnhandledMatchError). catch (Exception) doesn't catch Error.
  • throw is an expression since PHP 8.0, usable after ??, in match arms, ternaries and arrow functions.
  • Throw when the caller can't continue; return null/false when "not found" is a normal answer.

Next: Custom Exceptions and Error Handling Strategy