HomePHP Page 2 - Error Handling for Dynamic Twitter Signature Images with PHP
Understanding error-handling - PHP
Over the course of my past two articles I’ve been showing you how to build a script capable of creating and displaying a dynamic signature image containing the latest status from a user’s Twitter feed. In the third installment in this series, I will be demonstrating how to add proper object-oriented error handling to the SignatureImage class.
Before we dive too far into today’s new code, it’s important that you understand the error-handling mechanisms available to you in PHP 5. To do that, you’ll need to familiarize yourself with PHP’s Exception class.
The Exception class provided by PHP is used to throw Exceptions in your application whenever errors occur. Those exceptions may then be caught and handled in a variety of ways according to your application’s needs. Let’s examine a very simple example of the use of a PHP exception.
$x = 0;
try {
if $x == 0 {
throw new Exception('Cannot divide by 0');
}
$y = 100 / $x;
}
catch (Exception $e) {
echo $e->getMessage();
}
This examines attempts to divide the 100 by some number in the variable $x. I’ve created an error state by setting $x equal to 0, since you cannot divide any number by 0. To prevent PHP from displaying an error for this division, I’ve surrounded the process in an If statement that first determines whether or not $x contains the value 0. To this point, this should all be fairly standard procedure since this is a classic example of error prevention.
Next, I’ve employed the use of exceptions. Whenever $x equals 0 this code will throw an exception with the message “Cannot divide by 0.” This is done using the throw statement. Notice the use of the “new” keyword. We want to throw a new instance of the Exception class while passing it a string that contains the error message.
This is sufficient to throw an Exception in PHP. However, we can’t actually do anything with that exception yet. For this to be effective, the code needs to be contained in a Try block. This tells PHP to be on the lookout for possible exceptions.
Whenever PHP encounters an exception within a Try block, it will halt execution of the Try block and look for the first Catch block to catch and handle the exception. In this case, the catch block simply writes the error message back. This is a very simple demonstration. You’ll see the true power of exceptions as you see them used in our application.