This post is part of a series about PHP exceptions and exception handling; the first post gave a basic overview of how they work and this one shows the information that is available from the exception object when an exception is caught.
Example Code
The following is an example function that will throw an exception. Then folllows a try .. catch block which will catch the exception. It's in the catch() block that we have access to the information stored in the exception object.
Available information
The exception object has several pieces of information available which can be retrieved through function calls. Each section below covers the various calls and shows example output for the above example. The echo $e->getFile() etc calls in the examples below occur within the catch() { } block above where it says "// exception handling goes here".
$e->getFile()
This contains the name of the file in which the exception occurred. This (or any of the other items below) could be sent in an email, logged to a file etc. In these examples I will echo them.
Output:
$e->getLine()
This contains the line number the exception occured on.
Output:
$e->getCode()
This contains the error code. In the example above it was the second parameter passed when "throw new Exception" was called. The meaning of the code will depend on the exception thrown.
Output:
$e->getMessage()
This contains the error message which is usually more meaningful than the error code. In the above example this was the first parameter passed when the exception was thrown.
Output:
$e->getTrace();
getTrace returns a backtrace to show the order of function calls that led to the exception in reverse order with the most recent function call first. In the above example there was only one function called to get the exception so the array returned from print_r returns just a single element. To return the information from print_r as a string for logging or email, pass true as the second parameter to the print_r call.
Output:
$e->getTraceAsString()
An alternative to the getTrace method is getTraceAsString() which returns the same sort of information as debug_print_backtrace() but in a string instead of to standard output. This is a more condensed version than getTrace.
Output:
$e->__toString()
__toString() returns a string containing the error message, file and line number, and the backtrace returned from getTraceAsString().
Output:
Exception Series
This is the second post in a weekly series of seven about PHP exceptions. Read the previous post "PHP Exceptions" and next post "Catch uncaught exceptions with PHP" and use the links below to subscribe to my RSS feed, by email, or follow me on Twitter or Facebook to keep up to date with my daily postings.
0 comments:
Post a Comment