Custom Exceptions and Exception Chaining

3.Custom Exceptions and Exception Chaining

M

In this chapter

We'll learn how to create your own exception classes, which of PHP's built-in SPL exceptions to extend, how to write useful messages and when codes matter, how to add data and named constructors to an exception, how a marker interface groups related exceptions, and how exception chaining keeps the original cause when one exception wraps another.

16–18 min

The Problem in Real Life

BookBay's booking code throws new RuntimeException("...") for everything. To show the right message, the booking page does if (str_contains($e->getMessage(), "already booked")). Yesterday Marcus reworded one message to "That slot is taken" — and the page started showing "Something went wrong" for every double booking.

Worse, when the database times out, the code catches the PDOException and throws new RuntimeException("Could not load booking"). The log says exactly that, and nothing more: the real database error is gone.

M

Messages are for people. Code should decide by type — and never throw away the cause.

Marcus

Matching Message Strings vs. Exception Types

A class per problem

SlotTakenException says what happened in its name. Code catches the type, not a sentence.

Data, not just text

An exception can carry the slot, the booking id or the customer as typed properties.

Keep the cause

A wrapping exception stores the original as previous, so the log shows both.

Custom Exceptions and Exception Chaining

Exceptions that speak your language: PHP's built-in exceptions describe technical problems; your application needs its own, named after what really went wrong. This chapter covers:

  • Custom exception classes: one class per kind of problem.
  • PHP's SPL exceptions: which built-in parent to choose.
  • Messages and codes: what to write, and when codes matter.
  • Data and named constructors: exceptions that carry facts, and marker interfaces.
  • Exception chaining: wrapping one exception in another.

Custom exception classes: a custom exception is just a class that extends Exception or one of its children: final class SlotTakenException extends DomainException {} — one line is enough. Its name is the important part: catch (SlotTakenException $e) can't break when someone rewords a message, and anyone reading the code sees which problems a function can cause. Name them after the problem, ending in Exception by convention, and put them next to the code that throws them, like BookBay\Booking\SlotTakenException.

Catching by type, not by message
<?php
final class SlotTakenException extends DomainException {}
final class ShopClosedException extends DomainException {}
function book(string $slot): void
{
throw new SlotTakenException("That slot is taken"); // reworded: nothing breaks
}
try {
book("2026-11-06 09:30");
} catch (SlotTakenException) {
echo "Please choose another time.\n";
} catch (ShopClosedException) {
echo "We're closed that day.\n";
}
// Please choose another time.

PHP's SPL exceptions: PHP's Standard PHP Library has ready-made exception classes in two families. LogicException and its children mean a bug in the calling code — something that should never happen in a correct program: InvalidArgumentException (an argument that makes no sense, like a negative price), DomainException (a value outside the business rules), LengthException, OutOfRangeException. RuntimeException and its children mean a problem that can only be found while running, even in correct code: UnexpectedValueException, OutOfBoundsException, OverflowException, UnderflowException, RangeException. A database outage is a RuntimeException; an unbookable slot is often modelled as a DomainException. Extending the right one lets general code catch whole families. The diagram and table below map them.

Table — Choosing a parent class
ProblemParent classWhy
Negative price passed to MoneyInvalidArgumentExceptionThe caller passed a nonsensical argument: a bug
Booking a slot outside opening hoursDomainExceptionBreaks a business rule
Booking 4812 doesn't existRuntimeException (or OutOfBoundsException)Only known when the database is asked
Database or SMS service downRuntimeExceptionA problem of the environment, not the code
Unexpected data from an APIUnexpectedValueExceptionA value that didn't match what was promised

PHP's SPL exceptions

Exception

two families

LogicException

a bug in the calling code

RuntimeException

found only while running

children

InvalidArgumentException · DomainException · LengthException · OutOfRangeException

fix the code that called

UnexpectedValueException · OutOfBoundsException · OverflowException · UnderflowException · RangeException

handle, retry or report

Messages and codes: the message is for developers and the log, so write the facts: "Slot 2026-11-06 09:30 is already booked", not "Error!". Don't put secrets in it — passwords, card numbers, full tokens — because messages end up in logs and error trackers. And don't show it to customers as it is; the text users see is chosen where the exception is caught (chapter 6). The code is an optional integer, second argument of the constructor. PHP code rarely needs it: the class already says what happened. Codes are useful for numbers that come from outside, like an SMS provider's error code — and note that PDOException uses a string code, the SQLSTATE like "HY000".

Data and named constructors: an exception is a normal class, so it can have typed properties: SlotTakenException can carry public readonly string $slot, and the page can suggest the next free time without parsing a sentence. A named constructor — a static method like SlotTakenException::at($slot) — builds the message in one place, so every throw is short and every message is consistent. One limit: getMessage(), getCode(), getFile() and the other methods of Exception are final — overriding them is an error ("Cannot override final method Exception::getMessage()"). Pass the text to parent::__construct() instead.

Typed data and a named constructor
<?php
declare(strict_types=1);
final class SlotTakenException extends DomainException
{
private function __construct(public readonly string $slot, ?Throwable $previous = null)
{
parent::__construct("Slot {$slot} is already booked", 0, $previous);
}
public static function at(string $slot): self
{
return new self($slot);
}
}
try {
throw SlotTakenException::at("2026-11-06 09:30");
} catch (SlotTakenException $e) {
echo $e->getMessage(), "\n"; // for the log
echo "Taken: ", substr($e->slot, 11), "\n"; // data for the page
}
// Slot 2026-11-06 09:30 is already booked
// Taken: 09:30

Marker interfaces: sometimes several unrelated exceptions belong together: SlotTakenException extends DomainException, ShopClosedException too, but BookingNotFoundException extends RuntimeException. An interface that extends Throwable — interface BookingException extends Throwable {} — can be implemented by all three, and catch (BookingException $e) catches every booking problem in one block, whatever its parent class. An interface with no methods, used only to label classes, is a marker interface. The diagram below shows one.

A marker interface groups exceptions with different parents

interface BookingException extends Throwable

no methods: only a label

implemented by

SlotTakenException

extends DomainException

ShopClosedException

extends DomainException

BookingNotFoundException

extends RuntimeException

so

catch (BookingException $e)

catches all three in one block

A marker interface
<?php
interface BookingException extends Throwable {}
final class SlotTakenException extends DomainException implements BookingException {}
final class BookingNotFoundException extends RuntimeException implements BookingException {}
foreach ([new SlotTakenException("09:30 taken"), new BookingNotFoundException("No booking 4812")] as $problem) {
try {
throw $problem;
} catch (BookingException $e) { // one catch for the whole family
echo get_class($e), ": ", $e->getMessage(), "\n";
}
}
// SlotTakenException: 09:30 taken
// BookingNotFoundException: No booking 4812

Exception chaining: when code catches a low-level exception and throws its own — a PDOException becomes DatabaseUnavailableException — the original must not be lost. The third constructor argument, $previous, stores it: new DatabaseUnavailableException("Could not load booking 4812", 0, $e), or with a named argument, previous: $e. getPrevious() returns it, and echoing the outer exception prints the whole chain, the original first, then "Next" and the wrapper. The log now shows what the application was doing and what really failed underneath. Chapter 7 explains when to wrap like this.

Chaining: wrap the cause, don't lose it
<?php
final class DatabaseUnavailableException extends RuntimeException {}
function loadBooking(int $id): array
{
try {
throw new PDOException("SQLSTATE[HY000] [2002] Connection refused"); // what the driver throws
} catch (PDOException $e) {
throw new DatabaseUnavailableException("Could not load booking $id", previous: $e);
}
}
try {
loadBooking(4812);
} catch (DatabaseUnavailableException $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
$cause = $e->getPrevious();
echo "caused by ", get_class($cause), ": ", $cause->getMessage(), "\n";
}
// DatabaseUnavailableException: Could not load booking 4812
// caused by PDOException: SQLSTATE[HY000] [2002] Connection refused
Echoing the outer exception prints the whole chain (shortened)
PDOException: SQLSTATE[HY000] [2002] Connection refused in main.php:8
Stack trace:
#0 main.php(15): loadBooking(4812)
#1 {main}
Next DatabaseUnavailableException: Could not load booking 4812 in main.php:10
Stack trace:
#0 main.php(15): loadBooking(4812)
#1 {main}

Other languages: custom exceptions look the same everywhere: class SlotTakenException extends Exception in Java, class SlotTakenError(Exception): pass in Python. Python chains with raise DatabaseUnavailable(...) from e, Java with a cause constructor argument — the same idea as PHP's previous. Java can also attach suppressed exceptions — ones thrown while closing resources in try-with-resources — to the main one with addSuppressed(). PHP doesn't support that: one exception has at most one previous, so if clean-up code in finally can fail too, catch and log that failure there.

Python: raise … from e chains the cause
# Python
class DatabaseUnavailable(Exception):
pass
try:
rows = db.query("SELECT ...")
except ConnectionError as e:
raise DatabaseUnavailable("Could not load booking 4812") from e

Key Takeaway

Create one exception class per kind of problem (final class SlotTakenException extends DomainException {}) so code catches by type instead of matching messages. Extend LogicException's family for bugs in calling code (InvalidArgumentException, DomainException) and RuntimeException's family for problems found only while running. Messages are factual, secret-free text for developers; codes are optional and mostly for external numbers. Exceptions can carry typed data and named constructors, but getMessage() and the other Exception methods are final. A marker interface extending Throwable groups related exceptions, and the previous argument chains a wrapped exception so the original cause is never lost.

Why This Matters

Custom exceptions turn failures into part of your design: a function's possible exceptions are as much its interface as its parameters. Frameworks are built this way — Laravel's ModelNotFoundException becomes a 404 because of its type, not its message.

Chaining is what makes production logs useful. "Could not load booking" alone sends you searching; "Could not load booking 4812, caused by Connection refused" tells you to check the database server.

BookBay now has SlotTakenException, ShopClosedException and BookingNotFoundException, all marked with BookingException, and database errors are wrapped with their cause. While testing, Mia meets a different kind of problem: a TypeError when a form sends the price as text, a JsonException from a broken settings file, and an "Allowed memory size exhausted" that no catch seems able to stop. Those are PHP's own errors — the next chapter.