PHP ErrorException Class



Introduction

PHP's Exception class implements the Throwable interface. ErrorException class extends the Exception class. ErrorException is meant to be explicitly thrown when you want to catch and handle errors that would otherwise be ignored, such as Notices or Warnings.

PHP core consists of following predefined error constants

Value Constant Description
1 E_ERROR Fatal run-time errors.
2 E_WARNING Run-time warnings (non-fatal errors).
4 E_PARSE Compile-time parse errors.
8 E_NOTICE Run-time notices.
16 E_CORE_ERROR Fatal errors that occur during PHP's initial startup.
32 E_CORE_WARNING Warnings (non-fatal errors) that occur during PHP's initial startup.
64 E_COMPILE_ERROR Fatal compile-time errors.
128 E_COMPILE_WARNING Compile-time warnings (non-fatal errors).
256 E_USER_ERROR User-generated error message.
512 E_USER_WARNING User-generated warning message.
1024 E_USER_NOTICE User-generated notice message.
2048 E_STRICT If Enabled PHP suggests changes to your code to ensure interoperability and forward compatibility of your code.
4096 E_RECOVERABLE_ERROR Catchable fatal error.
8192 E_DEPRECATED Run-time notices.
16384 E_USER_DEPRECATED User-generated warning message.
32767 E_ALL All errors and warnings, E_STRICT

In addition to properties and methods inherited from Exception class, ErrorException class introduces one property and one method as follows −

protected int severity ;
final public getSeverity ( void ) : int

The severity of exception is represented by integer number associated with type of error in above table

ErrorException example

In following script, a user defined function errhandler is set as Error handler with set_error_handler() function. It throws ErrorException when fatal error in event of file not found for reading is encountered.

Example

 Live Demo

<?php
function errhandler($severity, $message, $file, $line) {
   if (!(error_reporting() & $severity)) {
      echo "no error";
      return;
   }
   throw new ErrorException("Fatal Error:No such file or directory", 0, E_ERROR);
}
set_error_handler("errhandler");
/* Trigger exception */
try{
   $data=file_get_contents("nofile.php");
   echo $data;
}
catch (ErrorException $e){
   echo $e->getMessage();
}
?>

Above example displays following output

Output

Fatal Error:No such file or directory
Updated on: 2020-09-21T11:25:22+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements