Blog |

PHP’s ErrorException Explained (with Example)

PHP’s ErrorException Explained (with Example)
Table of Contents

The PHP ErrorException class is meant to be thrown explicitly to catch and handle errors that would otherwise be ignored, such as Notices or Warnings.

ErrorException Class Hierarchy

The PHP Exception class implements the Throwable interface. The ErrorException class extends the Exception class.

 
Throwable
    └── Exception
                └── ErrorException

When to Use ErrorException

The ErrorException class can be used when an exception needs to be thrown and handled like a regular object inherited from the Exception class.

An example is when PHP issues a Warning. Depending on how the code is configured, warnings are ignored in PHP and execution continues as normal. In cases where a Warning indicates a failure that should redirect (or halt) script execution, the ErrorException class can be used.

PHP ErrorException Example

Here's an example of using the PHP ErrorException to produce an exception instead of a Warning:

A file is attempted to be accessed using the file_get_contents() function:

<?php
   file_get_contents("myfile.txt");
?>

When the above script is executed, a Warning is generated if the file could be found:

Warning:  file_get_contents(myfile.txt): failed to open stream: No such file or directory

If throwing an exception is more desirable than a Warning for such a case, the ErrorException class can be used to do so. The above example can be modified to use an error handler function to throw an ErrorException:

<?php
function errorHandler($severity, $message, $file, $line) {
   if (!(error_reporting() & $severity)) {
      return;
   }
   throw new ErrorException("Error: No such file or directory", 0, E_ERROR);
}

set_error_handler("errorHandler");

try {
   file_get_contents("myfile.txt");
} catch (ErrorException $e) {
   echo $e->getMessage();
}
?>

When the above script is executed, the errorHandler function throws an ErrorException instead of a Warning if the file is not found:

Error: No such file or directory

Here, the ErrorException is thrown and handled like a regular exception. If needed, the script execution can be redirected or halted in such cases, instead of continuing.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape