Home / Catch uncaught exceptions with PHP

Catch uncaught exceptions with PHP

This is the third in a series of posts about exception handling in PHP and looks at how to specify a default exception handler. The default handler is called for any exceptions that occur which are not enclosed in a try..catch block.

Normally catch exceptions in a try..catch block

If an exception is handled inside a try..catch block it will not result in an error. For example no error will be output using the code below, unless you choose to echo something in the catch section.

try {
    throw new Exception("This is an example exception");
}
catch(Exception $e) {
   
}

When an exception occurs that is not in a try..catch block

However, if the exception occurs and is not inside a try..catch block:

throw new Exception("This is an example exception");

then an error will be echoed to standard output:

Fatal error: Uncaught exception 'Exception' with message 'This is an example exception' in /common/websites/test/exceptions-example.php:5
Stack trace:
#0 {main}
  thrown in /common/websites/test/exceptions-example.php on line 5

Creating an exception handler

Normally you’d put something which could possibly have an exception into a try..catch block but it’s possible instead to handle all exceptions with a specified exception handler using the set_exception_handler() function.

This may not necessarily be the best practise but it is possible to do and may help catch out errors in your code which you may not have realised could throw an exception.

This is done by defining an exception handling function and setting it like so:

set_exception_handler('my_exception_handler');

function my_exception_handler($e) {
    // do some erorr handling here, such as logging, emailing errors
    // to the webmaster, showing the user an error page etc
}

Now when any exception occurs that is not handled by a try..catch block it will run the my_exception_handler() function. Obviously you can call your own exception handler whatever you want it to be.

Exception Series

This is the third post in a weekly series of seven about PHP exceptions. Read the previous post "PHP Exceptions – available information", the next post"Replace error reporting with exception handlers with PHP" and use the links below to subscribe to my RSS feed, by email, or follow me on Twitter or Facebook to keep up to date with my daily postings.