Custom Exception Types

Custom Exception Types in PHP: --- When a hospital receives casualties from a large incident, staff do not shout a single undifferentiated "something is wrong"…


The Analogy: The Hospital Triage Tags

When a hospital receives casualties from a large incident, staff do not shout a single undifferentiated "something is wrong" for every patient. They attach triage tags -- colour-coded, categorised labels that say precisely what kind of problem each patient has: red for immediate, yellow for delayed, green for minor, plus notes on the specific injury. The tag lets any clinician down the line, without re-examining the patient, route them to the right treatment instantly. A custom exception type is that triage tag: instead of throwing a generic error, you throw a specifically-named exception that tells every handler up the stack exactly what kind of failure occurred.

The tags form a deliberate classification, often hierarchical. "Trauma" is a broad category; "head trauma" and "limb fracture" are specific kinds within it. A specialist reads the specific tag; a general receiving doctor may act on just the broad category. Custom exceptions work the same way through class inheritance: a base PaymentException groups all payment failures, while CardDeclinedException and InsufficientFundsException are specific subtypes. A handler can catch the specific type when it has a tailored response, or catch the base type to handle the whole family uniformly.

A good tag carries more than a category -- it records structured details: blood pressure, allergies, the time of injury. These travel with the patient so no information is lost between departments. A well-designed custom exception likewise carries structured context as typed properties: an HTTP status code, the offending order reference, a map of validation errors. The handler reads these properties directly rather than parsing them out of a free-text message, which is fragile and lossy.

The failure mode is the hospital that tags every patient "unwell" and writes the details only in a scribbled note pinned to the gown. Downstream staff must stop and read the prose to guess the category, and two departments may read it differently. In code this is throwing a generic Exception with all the meaning buried in the message string, forcing handlers to match on substrings like str_contains($e->getMessage(), 'not found'). That coupling is brittle: reword the message and every handler breaks. The whole point of a typed exception is that the type and its properties carry the meaning structurally, so no handler ever has to parse prose to decide what happened.


Syntax or Core Structure

You define a custom exception by extending Exception or one of its subclasses. Adding a typed property -- via constructor promotion -- lets the exception carry structured context beyond the message.

<?php
declare(strict_types=1);

final class HttpException extends RuntimeException {
    public function __construct(
        public readonly int $status,
        string $message,
    ) {
        parent::__construct($message);
    }
}

function fetch(string $path): string {
    throw new HttpException(404, "not found: $path");
}

try {
    fetch('/missing');
} catch (HttpException $e) {
    echo 'status: ', $e->status, "\n";
    echo 'message: ', $e->getMessage(), "\n";
}

Output:

status: 404
message: not found: /missing

HttpException extends RuntimeException and adds a promoted readonly int $status property, passing the message up to the parent constructor. The handler reads $e->status directly -- 404 -- as a typed integer, and getMessage returns the human text. The status is structured data, not something a handler must extract from the message string, which is exactly the advantage a custom type gives you.


Technical Depth: Hierarchies, Named Constructors, and Rich Context

Choosing a base and building a hierarchy

The standard library offers a family of base types that already express intent, and you extend the closest fit rather than always extending Exception directly.

BaseSignals
LogicExceptionA bug: misuse the programmer should fix
RuntimeExceptionA runtime condition: bad input, missing resource
InvalidArgumentExceptionA specific bad argument (under Logic)
DomainExceptionA value outside the domain's valid set

Grouping your own exceptions under a shared base lets a handler catch the whole family or a single member.

<?php
declare(strict_types=1);

abstract class PaymentException extends RuntimeException {}
final class CardDeclinedException extends PaymentException {}
final class InsufficientFundsException extends PaymentException {}

function charge(string $kind): void {
    match ($kind) {
        'declined' => throw new CardDeclinedException('card declined'),
        'funds'    => throw new InsufficientFundsException('insufficient funds'),
        default    => print("charged ok\n"),
    };
}

foreach (['ok', 'declined', 'funds'] as $kind) {
    try {
        charge($kind);
    } catch (InsufficientFundsException $e) {
        echo 'specific: ', $e->getMessage(), "\n";
    } catch (PaymentException $e) {
        echo 'payment: ', get_class($e), "\n";
    }
}

Output:

charged ok
payment: CardDeclinedException
specific: insufficient funds

The ok case charges normally. A declined card throws CardDeclinedException, which is not InsufficientFundsException, so it falls to the base PaymentException handler. Insufficient funds throws the specific type caught by the first handler. The abstract base means "any payment failure" is one catch, while a subtype needing special treatment gets its own -- the same specific-before-general ordering, now over your own hierarchy.

Named constructors for common cases

A static factory method -- a "named constructor" -- makes the common way of building an exception readable and centralises the construction logic.

<?php
declare(strict_types=1);

final class ValidationException extends RuntimeException {
    /** @param array<string,string> $errors */
    public function __construct(public readonly array $errors) {
        parent::__construct('validation failed with ' . count($errors) . ' errors');
    }
    public static function field(string $name, string $problem): self {
        return new self([$name => $problem]);
    }
}

try {
    throw ValidationException::field('email', 'is invalid');
} catch (ValidationException $e) {
    echo $e->getMessage(), "\n";
    foreach ($e->errors as $field => $problem) {
        echo "  $field: $problem\n";
    }
}

Output:

validation failed with 1 errors
  email: is invalid

The exception carries a structured errors array as a typed property, and its message is derived from that array's count. The field named constructor builds the common single-field case cleanly, without the caller assembling an array by hand. The handler iterates $e->errors directly -- structured data, not parsed text -- printing each field and its problem. This is how a validation layer hands rich failure detail to the layer that renders it.

Marker interfaces for package-wide catches

Sometimes exceptions that must extend different bases still need a shared catchable identity. A marker interface -- an empty interface every package exception implements -- solves this without forcing a common base class. This is the pattern PSR libraries use so a caller can catch "any error from this package".

<?php
declare(strict_types=1);

interface CacheError {}

final class CacheMissException extends RuntimeException implements CacheError {}
final class CacheConnectionException extends RuntimeException implements CacheError {}

function readCache(string $key): string {
    throw new CacheMissException("no entry for $key");
}

try {
    readCache('user:1');
} catch (CacheError $e) {
    echo 'cache problem: ', $e->getMessage(), "\n";
    echo 'is a RuntimeException too? ', ($e instanceof RuntimeException ? 'yes' : 'no'), "\n";
}

Output:

cache problem: no entry for user:1
is a RuntimeException too? yes

Both cache exceptions extend RuntimeException but also implement the empty CacheError interface. The handler catches CacheError, which matches any exception the package marks, regardless of its base class -- and the caught object is still a RuntimeException, so nothing is lost. This decouples "which library raised this" from "what standard base it extends", letting a caller catch a whole package's failures with one interface while each exception still extends the most fitting base.


Real World Example: A Typed Exception Tree for Orders

An order-placement domain has several distinct failure modes -- out of stock, payment declined -- that all share a need to carry the order reference. A shared abstract base holds the common context, subtypes name the specific failures, and one handler covers the whole tree while the type still tells you what went wrong.

<?php
declare(strict_types=1);

abstract class OrderException extends RuntimeException {
    public function __construct(
        public readonly string $orderRef,
        string $message,
    ) {
        parent::__construct($message);
    }
}
final class OutOfStockException extends OrderException {}
final class PaymentFailedException extends OrderException {}

final class Orders {
    private array $stock = ['WIDGET' => 3, 'GADGET' => 0];

    public function place(string $ref, string $sku, bool $cardOk): string {
        $have = $this->stock[$sku] ?? 0;
        if ($have < 1) {
            throw new OutOfStockException($ref, "out of stock: $sku");
        }
        if (!$cardOk) {
            throw new PaymentFailedException($ref, 'card declined');
        }
        $this->stock[$sku]--;
        return "order $ref placed";
    }
}

$orders = new Orders();
$attempts = [
    ['R1', 'WIDGET', true],
    ['R2', 'GADGET', true],
    ['R3', 'WIDGET', false],
];

foreach ($attempts as [$ref, $sku, $cardOk]) {
    try {
        echo $orders->place($ref, $sku, $cardOk), "\n";
    } catch (OrderException $e) {
        $kind = (new ReflectionClass($e))->getShortName();
        echo "order {$e->orderRef} failed [$kind]: {$e->getMessage()}\n";
    }
}

Output:

order R1 placed
order R2 failed [OutOfStockException]: out of stock: GADGET
order R3 failed [PaymentFailedException]: card declined

Order R1 succeeds. R2 requests the out-of-stock GADGET, throwing OutOfStockException; R3 has a declined card, throwing PaymentFailedException. Both are OrderException subtypes, so one catch (OrderException $e) handles them, and the promoted orderRef property is available on every one -- the shared context lives in the base. The handler uses the concrete class name to report which kind of failure occurred, all without parsing the message text.

The design flaw is the handler's use of the concrete class short-name as a user-facing or log-facing category, which silently couples external behaviour to internal class names. Rename OutOfStockException to StockUnavailableException in a refactor and every log line, every dashboard that groups by that string, and any client that switched on it now sees a different category for the identical failure -- a breaking change disguised as a harmless rename. The class name is an implementation detail; the stable, external identity of a failure kind should be an explicit, deliberately-chosen value -- a string constant or enum case like OrderException::CODE_OUT_OF_STOCK -- that the refactor cannot accidentally change. Deriving the category from the class name via reflection is convenient but conflates "what the class is called in the source" with "what this failure is called to the outside world", and those must be allowed to diverge. A robust design gives each exception subtype an explicit stable code, and the handler reports that, so internal renames stay internal.


Common Mistakes

  1. Encoding meaning in the message string. Forcing handlers to match on str_contains($e->getMessage(), ...) is brittle. Put the meaning in the type and typed properties.
  1. Extending Exception for everything. Ignoring the standard bases loses expressed intent. Extend the closest fit -- RuntimeException, LogicException, and so on.
  1. A flat pile of unrelated exceptions. With no shared base, you cannot catch a family at once. Group related exceptions under a common abstract base.
  1. Overusing custom types. Inventing an exception class for every conceivable case bloats the codebase. Create a type when handlers actually need to distinguish it.
  1. Coupling external identity to the class name. Using the class name as a log or API category means a rename is a breaking change. Give each type an explicit stable code.
  1. Forgetting to call the parent constructor. Adding a constructor without parent::__construct can lose the message. Always pass the message and any cause up.
  1. Dropping the previous exception. A custom exception that wraps a cause should accept and forward it, so getPrevious still works.
  1. Mutable exception state. Public writable properties let handlers alter the exception. Make context properties readonly so the failure record is immutable.
  1. Throwing the base abstract type. If a base is abstract to force specificity, do not try to instantiate it. Throw a concrete subtype that names the actual failure.

Best Practices

  • Put failure meaning in the exception type and its typed properties, never in a message string handlers must parse.
  • Extend the most specific standard base that fits, so the exception's intent is clear before you add anything.
  • Group related exceptions under a shared abstract base, enabling both family-wide and specific catches.
  • Carry structured context -- codes, references, error maps -- as readonly promoted properties, keeping the record immutable.
  • Provide named constructors for common construction patterns, centralising and clarifying how the exception is built.
  • Give each exception kind an explicit, stable code or enum for external identity, so internal renames do not break clients or logs.
  • Forward a wrapped cause via the parent constructor's third argument, preserving the chain.
  • Create a custom type only when a handler genuinely needs to distinguish it, avoiding a class explosion.

Practice Exercises

  1. Define an HttpException extending RuntimeException with a promoted readonly int $status, throw it, and have the handler read the status as a typed integer.
  1. Build an abstract PaymentException base with CardDeclinedException and InsufficientFundsException subtypes, and demonstrate catching one specifically and the other via the base.
  1. Write a ValidationException that carries an errors array and a field named constructor, then catch it and iterate the structured errors.
  1. Create an order exception tree sharing an orderRef in the base, add an explicit stable code per subtype, and have one handler report that code rather than the class name.