In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
getMessage(): Returns the message if it is passed to the constructor.
getCode(): Returns the error code if it is passed to the constructor.
getLine(): Returns the line number for which the exception is thrown.
getFile(): Returns the name of the file throwing the exception.
getTrace(): Returns an array consisting of information pertinent to the context in which the error occurred. Specifically, this array includes the file name, line, function, and function parameters.
getTraceAsString(): Returns all of the same information as is made available bygetTrace(), except that this information is returned as a string rather than as an array.
Caution Although you can extend the exception base class, you cannot override any of the preceding methods because they are all declared asfinal. See Chapter 6 more for information about thefinalscope.
Listing 8-1 offers a simple example that embodies the use of the overloaded base class constructor, as well as several of the methods.
Listing 8-1. Raising an Exception
try {
$fh = fopen("contacts.txt", "r"); if (! $fh) { throw new Exception("Could not open the file!"); } } catch (Exception $e) { echo "Error (File: ".$e->getFile().", line ". $e->getLine()."): ".$e->getMessage(); }
If the exception is raised, something like the following would be output:
--------------------------------------------
Error (File: /usr/local/apache2/htdocs/8/read.php, line 6): Could not open the file!