Back to results for “Error Handling”
PHP › Error & Exception Handling

How do you create and throw a custom exception class in PHP, and why would you define your own exception types instead of using PHP's built in generic Exception class?

Intermediate

Answer

You create a custom exception by defining a class that extends PHP's built in Exception class, or a more specific built in exception, optionally adding your own additional properties or methods, and defining custom exception types lets calling code catch and respond to very specific error conditions distinctly, such as differentiating between an InsufficientFundsException and a generic database error, rather than needing to inspect a generic exception's message text to determine what actually went wrong.
class InsufficientFundsException extends Exception {
    public function __construct(private float $shortfall) {
        parent::__construct("Insufficient funds, short by $shortfall");
    }
    public function getShortfall(): float { return $this->shortfall; }
}
Real-world example A banking application throws a custom InsufficientFundsException when a withdrawal exceeds the available balance, letting the calling code specifically catch this exception type and display a precise, helpful message rather than a generic error.

Common follow-ups: Should custom exceptions extend the base Exception class or a more specific built in exception like InvalidArgumentException?;How many custom exception classes is reasonable for a typical application to define?