367 of 410 menu

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

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

Code execution result:

'Error: Critical error Severity: 1'

Example

Let's convert standard PHP errors into exceptions:

<?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):

'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 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:

'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
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline