PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

An exception is a special object instantiated from the built-in Exception class (or from a derived
class). Objects of type Exception are designed to hold and report error information.
The Exception class constructor accepts two optional arguments, a message string and an error
code. The class provides some useful methods for analyzing error conditions. These are described in
Table 4–1.


Table 4–1. The Exception Class’s Public Methods


Method Description

getMessage() Get the message string that was passed to the constructor.

getCode() Get the code integer that was passed to the constructor.

getFile() Get the file in which the exception was generated.

getLine() Get the line number at which the exception was generated.

getPrevious() Get a nested Exception object.

getTrace() Get a multidimensional array tracing the method calls that led to the
exception, including method, class, file, and argument data.

getTraceAsString() Get a string version of the data returned by getTrace().

__toString() Called automatically when the Exception object is used in string context.
Returns a string describing the exception details.

The Exception class is fantastically useful for providing error notification and debugging
information (the getTrace() and getTraceAsString() methods are particularly helpful in this regard). In
fact, it is almost identical to the PEAR_Error class that was discussed earlier. There is much more to an
exception than the information it holds, though.


Throwing an Exception


The throw keyword is used in conjunction with an Exception object. It halts execution of the current
method and passes responsibility for handling the error back to the calling code. Here I amend the
__construct() method to use the throw statement:


function __construct( $file ) {
$this->file = $file;
if (! file_exists( $file ) ) {
throw new Exception( "file '$file' does not exist" );
}
$this->xml = simplexml_load_file($file);
}


The write() method can use a similar construct:

function write() {
if (! is_writeable( $this->file ) ) {

Free download pdf