Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 4 ■ EXCEPTIONS^33

Once constructed, an exception knows several key things: where it was constructed, what
code was executing at the time of construction, and the error message and the error code.
Table 4-1 lists the methods that provide this data.

The getTrace() method is very useful because each key in the array also contains the file, line,
function name, and most important, all the arguments with which the function was called. Using
the backtrace information, you can see all the upstream data that caused the problem, simplifying
debugging. The getTrace() method is similar to the built-in function debug_backtrace().
Listing 4-1 demonstrates exception logic in the context of a database connection.

Listing 4-1. Throwing an Exception While Connecting to a Database

function connectToDatabase() {

if(!$conn = pg_connect(...)) {
throw new Exception("Could not connect to the database");
}

}

try {

connectToDatabase();

} catch(Exception $e) {

echo $e->getMessage();

}

Table 4-1. Exception Methods
Method Description
getMessage() Returns the exception message, which is a string describing the
error state
getCode() Returns the error code
getFile() Returns the source file in which the error occurred; useful for
locating where an exception was thrown
getLine() Gets the line in the source file where the exception was thrown;
should be used with getFile()
getTrace() Returns an array containing the context backtrace, which is a list of
all the methods that are currently executing and their order
getTraceAsString() Same as getTrace(), but returned as a string instead of an array
__toString() Returns the entire exception represented as a string

McArthur_819-9C04.fm Page 33 Friday, February 1, 2008 10:25 AM

Free download pdf