Welcome to the last part of the series “Error Handling in PHP.” In two parts, this series introduces the basics of error handling in PHP. It demonstrates some of the most common methods for manipulating errors in PHP 4, and explains the implementation of exceptions in PHP 5, particularly in object-oriented environments.
As I mentioned earlier, it’s possible to get detailed information about the error that occurred. It’s precisely for this reason that the Exception class provides developers with some other methods, which can offer additional details about the failure and its environment. Here is the sample “FileReader” class, which now uses these complementary methods:
class FileReader{ private $file; private $fileDir='fileDir/'; public function __construct($file){ if(!file_exists("{$this->fileDir}{$file}.php")){ throw new Exception('File '.$file.' not found'); } $this->file=$file; } public function getContent(){ if(!$content=file_get_contents("{$this->fileDir}{$this- >file}.php")){ throw new Exception('Unable to read file contents'); } return $content; } }
In addition to the methods illustrated above, the Exception class exposes the “getTrace()” and “getTraceAsString()” methods. The first one returns an array providing information on the progress of an exception, while the second one shows the same data, but in string format.
Returning to the example above, it’s nearly the same as the previous one. However, the “catch” block uses the additional methods of the exception object, helpful for obtaining more specific details on the error that occurred. With reference to this, the set of “echo” statements displays the error message passed in when the exception was originally thrown, as well as the error code (if any), the file containing the error, and finally the line at which the failure happened.
Now, the benefits of exceptions should be pretty clear. Notice how easy it is to set up an error management mechanism that can be developed through specific code, while maintaining program flow completely free from dealing with potential failures. In addition, as you’ve seen in the above example, a greater level of detail on the error that occurred can be easily obtained by calling up some of the complementary methods.
What else can we ask for? Well, sometimes it’s highly advantageous to have an error handling system that is capable of determining what course of action to take, according to the type of error generated. While this may sound like common sense stuff, in practical terms, it isn’t so intuitive to code. Thus, let’s address this issue and set up an example, which takes different actions according to the type of exception generated.