0PricingLogin
PHP Academy · Lesson

Creating Custom Exceptions

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

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;
    }
}

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