PHP
PHP 8.2 Documentation / Exceptions / ErrorException

ErrorException

PHP 8.2 • Exception Handling

Overview

The ErrorException class wraps traditional PHP errors into manageable exceptions, allowing them to be caught and handled with try-catch blocks.

Usage

Error to Exception Conversion

<?php
set_error_handler(function ($severity, $message, $file, $line) {
    if (error_reporting() & $severity) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
    return true;
});
?>

Register a callback to convert errors like E_WARNING to ErrorException instances.

Methods

getMessage()

Returns the raw error message string

getCode()

Returns the error code as an integer

getFile()

Returns the filename where the error occurred

getLine()

Returns the line number of the error

Best Practices

  • Use in try-catch: Wrap error-prone code in try blocks for clean error recovery.
  • Custom Error Types: Extend ErrorException for application-specific error categorization.
  • Logging: Convert to PSR-3 compliant log entries for monitoring systems.

See Also

set_error_handler()

Convert errors to exceptions
Tip: Use Error class for error objects not wrapping PHP errors.
```