The Standard PHP Library, Part 1 - Simple Example (
Page 2 of 4 )
Now that we have covered the basics of what an exception is, we will look at a code snippet to see them in action.
class Math {
function divide($divisor, $dividend = 1) {
if (!is_numeric($divisor))
throw(new Exception('Divisor is not a number'));
if (!is_numeric($dividend))
throw(new Exception('Dividend is not a number'));
if ($dividend == 0)
throw(new Exception('Division by zero'));
return ($divisor / $dividend);
}
}
try {
print Math::divide(1, 0);
}
catch(Exception $e) {
print $e;
}
If you run this code sample, you will see a dump of the contents of the exception thrown by our divide function. The object contains a lot of useful info like the file name and line where the error occurred and the trace. If you are logging errors or displaying them to the screen (for debugging), this information is priceless. Let's go over the important parts of this code.
if (!is_numeric($divisor))
throw(new Exception('Divisor is not a number'));
if (!is_numeric($dividend))
throw(new Exception('Dividend is not a number'));
if ($dividend == 0)
throw(new Exception('Division by zero'));
This piece of code checks to see if the divisor and dividend are numbers and if the dividend is a non-zero value. If any of these checks fail, our method calls the new function "throw()", passing it a new Exception object. We send our message to the constructor of Exception so the debugging information is descriptive enough to be of use and to indicate the specific type of failure encountered by the function. Exceptions can also be extended to give them meaningful names, such as DivisionByZeroException for our case, but in general supplying a suitably descriptive message is adequate.
try {
print Math::divide(1, 0);
}
Here we attempt to call "divide()". Placing it in a "try" control structure allows us to logically separate our code blocks, as not all operations require exception handling. We could generate other errors by making calls to divide with non-numeric input.
catch(Exception $e) {
print $e;
}
This is where the exception is actually caught for handling. We could do something with this error, such as tell the user they cannot divide by zero with the "divide()" function, but in this case we are simply invoking the "$e->__toString()" magic method by treating "$e" as a string - ultimately yeilding an informative error message for the developer.