Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 147 ยท Errors and Exceptions

Custom Exceptions and Error Handling Strategy

Create your own PHP exception classes, chain exceptions with previous, turn warnings into ErrorException, add a global handler and decide what to catch where.

The built-in exception classes from the previous lesson tell you what kind of thing went wrong: an invalid argument, a runtime failure. Real applications need more precise names. "The customer's card was declined" and "the payment service is down" are both runtime failures, but a checkout page must react to them very differently: one shows a message to the customer, the other retries or alerts the team. Your own exception classes make that distinction part of the type system, so a catch block can pick exactly the failures it knows how to handle.

This lesson shows how to design exception classes, attach extra data to them, wrap low-level exceptions without losing the original cause, turn PHP's old-style warnings into exceptions, and install a last-resort handler. It ends with the most important part: a strategy for deciding where exceptions should be caught.

Creating an exception class

A custom exception is an ordinary class that extends one of the built-in ones. The smallest version has no body at all:

PHP
final class InsufficientStockException extends RuntimeException
{
}

That's already useful: callers can now write catch (InsufficientStockException $e) and ignore every other runtime failure. Choose the parent that matches the meaning:

  • extend RuntimeException (or one of its subclasses) for failures that depend on the outside world or the current state: stock ran out, a file vanished, an API timed out;
  • extend LogicException, often InvalidArgumentException or DomainException, for calls that are wrong no matter when they happen: a negative quantity, an unknown currency code.

Never extend Error for your own classes. That family belongs to the engine, and code that catches Exception won't see it.

Adding data and named constructors

Exceptions can carry more than a message. Add read-only properties for the details a handler needs, and use static named constructors so each throw site reads like a sentence and the message format lives in one place:

PHP An exception class with data and a named constructor

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 reservation succeeds; the second throws, and the handler uses the available property to make a better offer instead of parsing the message text. The constructor is private, so the named constructor is the only way to create the exception and every message has the same format. The constructor property promotion and readonly syntax keep the class short.

Messages are for humans reading logs; properties and types are for code. Never make a catch block depend on the wording of getMessage(), because someone will rephrase it.

A family of exceptions for one module

Libraries and larger modules often define a marker interface that all their exceptions implement. Callers can then catch "anything from the payments module" in one block, while each class still extends the most fitting SPL parent:

PHP A marker interface for a module's exceptions

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 declined card gets its own message; the invalid amount falls through to the PaymentException block. An interface used this way must extend Throwable, and only classes that extend Exception or Error can implement it.

Chaining exceptions with previous

When a low-level operation fails, you often want to throw an exception that makes sense at your level ("could not save the order") without losing the low-level details ("UNIQUE constraint failed"). Every exception constructor takes a third argument, $previous, for exactly this. The new exception wraps the old one, and getPrevious() gets it back:

PHP Wrapping a PDOException with previous

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 output is:

TEXT
OrderNotSavedException: Order A-1001 could not be saved
  caused by PDOException: SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: orders.reference

The caller only needs to know about OrderNotSavedException, so it doesn't depend on PDO at all; you could swap the database for an API later. Yet nothing is lost: when an exception with a previous goes uncaught, PHP prints the whole chain, each part with its own stack trace, separated by Next. Error trackers show the chain too. (The PDO lessons explain the database code.)

When you catch and rethrow, always pass the original as previous. throw new OrderNotSavedException('...') without it throws away the real reason, and you'll be debugging a message that says "could not be saved" with no idea why.

Turning warnings into exceptions with ErrorException

Many built-in functions still report failure the old way: a warning plus a false return value. Errors, Warnings and Notices showed that you can install your own error handler. The classic handler throws an ErrorException, so every warning, notice and deprecation becomes a real exception that stops the code:

PHP An error handler that throws ErrorException

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.

Without the handler, readConfig() would print a warning and return false, which would then violate its string return type and cause a confusing TypeError later. With it, the failure is caught at the right place with the real message. ErrorException adds a severity (the original error level) to the normal exception data. The second block shows that even an undefined array key now stops the code: Caught: Undefined array key "coffee" on line 26.

This is what Laravel, Symfony and most frameworks do. It makes PHP behave like a strict language: no silent null guesses.

A last-resort handler: set_exception_handler

set_exception_handler() registers a function that PHP calls for any exception nobody caught. It's the place to log the problem and show a friendly page instead of a stack trace. After the handler runs, the script ends; there's no way to "resume".

PHP A global exception handler

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 second loadDashboard() call passes null, so $widget->render() throws Error: Call to a member function render() on null. Nothing catches it, so the handler logs it and prints the apology. Notice the handler's parameter is Throwable, so it receives Errors as well as Exceptions. On a web server you'd also send status 500 (see HTTP Headers and Status Codes), and in development you'd let the full trace show.

Keeping secrets out of stack traces

Stack traces include the arguments of every function call. That's helpful for debugging, but it means a password or API key passed to a function can end up in your logs. PHP 8.2 added the #[\SensitiveParameter] attribute: mark a parameter with it and traces show a placeholder instead of the value.

PHP Hiding a parameter from traces

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 trace prints #0 main.php(10): login('[email protected]', Object(SensitiveParameterValue)): the email is visible, the password isn't. (Traces cut string arguments after 15 characters, so long values appear shortened with ....)

Strategy: what to catch, and where

Knowing the syntax is the easy part. These rules decide whether exceptions make your code robust or just noisy.

1. Catch only what you can handle. A catch block must do something meaningful: retry, use a fallback, show the user a specific message, or translate the exception into one at your level (with previous). If you can't do any of those, don't catch; let the exception travel up.

2. Never swallow exceptions silently. This is the worst habit in error handling:

PHP
try {
    $mailer->send($message);
} catch (Exception $e) {
    // ignore
}

The email silently isn't sent and nobody ever finds out. If ignoring is truly right, at least log it and write a comment saying why.

3. Handle errors at boundaries. Most exceptions should be caught in a few places, not in every function:

Layer Typical handling
Domain and service code Throws specific exceptions (InsufficientStockException); rarely catches
Infrastructure (database, files, HTTP clients) Catches technical exceptions and rethrows them as your own, with previous
Controllers, CLI commands, queue jobs Catch domain exceptions they can turn into a response: a form error, a 404, a retry
The front controller / global handler Catches Throwable: logs, sends 500, shows a friendly page

4. Log once. If every layer logs and rethrows, one failure produces five log entries. Log where the exception is finally handled, usually the global handler.

5. Keep the original. Rethrow with previous, or rethrow the same object with a bare throw $e;, which keeps the original trace and line.

6. Clean up with finally, not catch. If you only need to release a resource, use try/finally and let the exception continue.

Here's the strategy in miniature: a small domain function, an infrastructure wrapper, and a "controller" that maps each exception to a response.

PHP Mapping exceptions to responses at the boundary

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 output is one line per request: 200 OK: 3.50 EUR, 404 Not Found: No product with SKU LAMP-9, and 503 Service Unavailable: please try again in a minute. findPrice() never thinks about HTTP; the controller never inspects messages. Anything else, like a TypeError, isn't caught here at all, and reaches the global handler as a 500.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You catch a PDOException and throw your own RepositoryException. What should you pass so the original cause is not lost?

    new RepositoryException('...', 0, $e) stores the original as previous. getPrevious() returns it, and uncaught chains print every link.
  2. 2. Which parent class fits an exception for "the shipping API timed out"?

    A timeout depends on the outside world at run time, which is what RuntimeException is for. Error and TypeError belong to the engine, and the argument wasn't invalid.
  3. 3. An error handler throws ErrorException. What does $prices['missing'] do now?

    The undefined key raises an E_WARNING, the handler receives it and throws, so the code stops unless something catches ErrorException.
  4. 4. What happens after a function registered with set_exception_handler() finishes?

    The exception handler is a last resort for uncaught exceptions. When it returns, the script terminates.
  5. 5. Which catch block is the most problematic?

    An empty catch for every Exception swallows failures silently. The others handle a specific case, translate with previous, or act as the top-level boundary.

Summary

  • Create exception classes by extending RuntimeException (outside-world and state failures) or LogicException/InvalidArgumentException/DomainException (wrong calls). Never extend Error.
  • Add read-only properties for data that handlers need, and static named constructors (::forItem()) for consistent messages. Code should check types and properties, not message text.
  • A marker interface extending Throwable lets callers catch every exception from one module.
  • Wrap low-level exceptions with the $previous argument; getPrevious() walks the chain, and uncaught chains print every link.
  • An error handler that throws ErrorException turns warnings into exceptions, as frameworks do.
  • set_exception_handler() is the last resort for uncaught Throwables: log, send 500, show a friendly page; the script then ends.
  • #[\SensitiveParameter] (PHP 8.2) keeps secrets out of stack traces.
  • Strategy: catch only what you can handle, never swallow silently, handle at boundaries, log once, keep the original, clean up with finally.

Next: Debugging PHP