The ErrorException Class

The ErrorException class inherits from the base Exception class and is used to convert PHP errors into exceptions. It adds information about the error severity to the standard exception functionality. The class is particularly useful when used with the set_error_handler function.

Syntax

phpnew ErrorException(
  string $message = "",
  int $code = 0,
  int $severity = E_ERROR,
  string $filename = __FILE__,
  int $lineno = __LINE__,
  Throwable $previous = null
);

Example

Let's create and handle an ErrorException:

php<?php
  try {
    throw new ErrorException('Critical error', 0, E_ERROR);
  } catch (ErrorException $e) {
    echo 'Error: ' . $e->getMessage();
    echo ' Severity: ' . $e->getSeverity();
  }
?>

Code execution result:

php'Error: Critical error Severity: 1'

Example

Let's convert standard PHP errors into exceptions:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Incorrect number of arguments
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Code execution result (example):

php'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'

Example

Let's get information about the error severity:

php<?php
  try {
    throw new ErrorException('Warning message', 0, E_WARNING);
  } catch (ErrorException $e) {
    echo 'Severity level: ' . $e->getSeverity();
    echo ' Is warning: ' . ($e->getSeverity() === E_WARNING ? 'yes' : 'no');
  }
?>

Code execution result:

php'Severity level: 2 Is warning: yes'

See Also

  • the Exception class,
    the base class for all exceptions in PHP
  • the set_error_handler function,
    which sets a user-defined error handler