The Exception Class

What you’re actually catching when PHP throws an exception is either an instance of the Exception class or a class that’s descended from Exception.

The methods of the Exception class provide you with easy access to the individual details of the exception, such as the message, error code, filename, and line number. Use them when the overview you get from printing an object doesn’t help you find the information you need.

For example, you might want to take different action based upon the specific error code stored in the exception. Some problems may be recoverable, while others aren’t.

Table 7-1 contains a list of all the exception methods and what they do.

Table 7-1. Exception methods

Method name

Description

getMessage( )

A text description of the error

getCode( )

A numeric error code

getFile( )

The filename where the error occurred

getLine( )

The line where the error occurred

getTrace( )

The array output of debug_backtrace( )

getTraceAsString( )

The string output of debug_print_backtrace( )

_ _toString( )

A comprehensive description of the exception

Example 7-5 calls four of the Exception class methods.

Example 7-5. Retrieving exception specifics

$version = '1.0'; $element = '&'; // & is an ILLEGAL element name try { $dom = new DOMDocument($version); $ab = new DOMElement($element); $ab = $dom->appendChild($ab); } catch (Exception $e) { error_log('Error in file ' . $e->getFile( ) . ' on line ' . $e->getLine( ) . ...

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.