0Pricing
PHP Academy · Lesson

Creating Custom Exceptions

Extend the Exception class to build domain-specific error types.

Creating Custom Exceptions is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Custom Exceptions?

Custom exceptions let you:

  • Distinguish your application errors from generic PHP errors
  • Carry domain-specific data (order ID, user ID, etc.)
  • Catch specific error types at different layers
  • Create meaningful, self-documenting error hierarchies

Extending Exception

Create a custom exception by extending the Exception base class:

<?php
class ValidationException extends \Exception
{
    private array $errors;

    public function __construct(array $errors, string $message = '', int $code = 0)
    {
        $this->errors = $errors;
        parent::__construct($message ?: implode(', ', $errors), $code);
    }

    public function getErrors(): array
    {
        return $this->errors;
    }
}

Using Custom Exception

Throw and catch your custom exception:

<?php
function createUser(array $data): void {
    $errors = [];
    if (empty($data['email'])) $errors[] = 'Email required';
    if (empty($data['name']))  $errors[] = 'Name required';

    if ($errors) {
        throw new ValidationException($errors);
    }
    // save user...
}

try {
    createUser([]);
} catch (ValidationException $e) {
    foreach ($e->getErrors() as $err) {
        echo '- ' . $err . PHP_EOL;
    }
}

Exception Hierarchy Design

Design a hierarchy for your domain:

<?php
// Base exception for your app
class AppException extends \RuntimeException {}

// Domain-specific exceptions
class NotFoundException extends AppException {}
class AuthException extends AppException {}
class PaymentException extends AppException {}

// Specific payment errors
class InsufficientFundsException extends PaymentException {
    public function __construct(public readonly float $balance, public readonly float $required) {
        parent::__construct("Insufficient funds: have $balance, need $required");
    }
}

Catching by Hierarchy

Catch a base class to handle all derived exceptions:

<?php
try {
    processPayment($order);
} catch (InsufficientFundsException $e) {
    echo 'Low balance: need ' . $e->required;
} catch (PaymentException $e) {
    echo 'Payment failed: ' . $e->getMessage();
} catch (AppException $e) {
    echo 'App error: ' . $e->getMessage();
} catch (\Throwable $e) {
    // Last resort
    error_log($e);
}

Adding Context to Exceptions

Enrich exceptions with additional data for debugging:

<?php
class HttpException extends \RuntimeException
{
    public function __construct(
        private int    $statusCode,
        string         $message = '',
        ?\Throwable    $previous = null
    ) {
        parent::__construct($message, $statusCode, $previous);
    }

    public function getStatusCode(): int
    {
        return $this->statusCode;
    }
}

HTTP Exception Example

Using the HTTP exception in a web application:

<?php
try {
    $user = findUserById($id);
    if (!$user) throw new HttpException(404, 'User not found');
    if (!$user->canAccess($resource)) {
        throw new HttpException(403, 'Access denied');
    }
} catch (HttpException $e) {
    http_response_code($e->getStatusCode());
    echo json_encode(['error' => $e->getMessage()]);
}

Interface-Based Exceptions

Use interfaces to group unrelated exception classes:

<?php
interface UserFacingException
{
    public function getUserMessage(): string;
}

class ValidationException extends \Exception implements UserFacingException
{
    public function getUserMessage(): string
    {
        return 'Please check your input: ' . $this->getMessage();
    }
}

// In controller:
catch (UserFacingException $e) {
    echo $e->getUserMessage();
}

Named Constructor Pattern

Use static factory methods for common exception scenarios:

<?php
class OrderException extends \RuntimeException
{
    public static function notFound(int $id): self
    {
        return new self("Order #$id not found", 404);
    }

    public static function alreadyShipped(int $id): self
    {
        return new self("Order #$id already shipped", 409);
    }
}

throw OrderException::notFound($orderId);

Serializing Exceptions

Convert exception data to an array for logging or API responses:

<?php
function exceptionToArray(\Throwable $e): array {
    return [
        'type'    => get_class($e),
        'message' => $e->getMessage(),
        'code'    => $e->getCode(),
        'file'    => $e->getFile(),
        'line'    => $e->getLine(),
        'trace'   => $e->getTraceAsString(),
        'previous' => $e->getPrevious()
            ? exceptionToArray($e->getPrevious())
            : null,
    ];
}

Best Practices for Custom Exceptions

Guidelines for designing custom exceptions:

  • Extend RuntimeException for unexpected conditions
  • Extend LogicException for programmer errors (invalid arguments)
  • Don't create an exception class for every possible message — use codes instead
  • Keep exception class names in PascalCase ending in Exception
  • Document which exceptions each method can throw

Quick Check

Which PHP base class should you extend to create a custom exception that represents a logical error in your code?

Recap: Custom Exceptions

Custom exceptions summary:

  • Extend Exception or a subclass
  • Add domain-specific properties and methods
  • Design hierarchies — catch parent to catch all children
  • Use interfaces to group unrelated exceptions
  • Use static named constructors for clarity
  • Always call parent::__construct()

Frequently asked questions

Is the “Creating Custom Exceptions” lesson free?

Yes — the full text of “Creating Custom Exceptions” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Creating Custom Exceptions”?

Extend the Exception class to build domain-specific error types. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Creating Custom Exceptions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. PHP Error Types and Reporting
  2. Try, Catch, and Finally
  3. Creating Custom Exceptions
  4. Logging Errors and Best Practices
← Back to PHP Academy