O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ) . ".\n" . 'Error ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required