Setting a Custom Exception Handler

PHP always dies with a fatal error whenever you fail to catch an exception. However, you can control what PHP does before it dies by creating a custom exception-handling function and registering it using set_exception_handler( ). For example:

function my_exception_handler($e) {
    error_log('Error in file ' . $e->getFile( ) . ' on line ' . 
       $e->getLine( ) . ".\n" . 'Error message: "' . $e->getMessage( ) . 
       '" and error code: ' . $e->getCode( ) . '.');
}

set_exception_handler('my_exception_handler');

$version = '1.0';
$element = '&'; // & is an ILLEGAL element name

$dom = new DOMDocument($version);
$ab = new DOMElement($element);
$ab = $dom->appendChild($ab);

Error in file /www/www.example.com/dom.php on line 14.
            Error message: "Invalid Character Error" and error code: 5.

Because the exception isn’t caught inside a catch block, the exception handler kicks in and prints the message to the error log. When the function finishes, PHP dies.

If you’re writing new PHP 5 code, there’s really no reason to use set_exception_handler( ), because you can just wrap the main section of your code inside a try/catch block. However, you may find it useful when converting older PHP 4 code that wasn’t designed with exception handling in mind over to PHP 5.

In particular, if you’re using set_error_handler( ) , adding a call to set_exception_handler( ) may be a good stop-gap method. It would allow you to handle exceptions like you’re already handling errors, without ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.