7.6 Setting a Custom Exception Handler

 <  Day Day Up  >  

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 being forced to restructure your code.

 <  Day Day Up  >  


Upgrading to PHP 5
Upgrading to PHP 5
ISBN: 0596006365
EAN: 2147483647
Year: 2004
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net