Understanding PHP Exception Handling

PHP 5 has an exception handling model similar to that of other programming languages. Exception handling is used primarily to modify the control of a program by using the “try” and “catch” method. Throwing and catching exceptions allow programmers to handle errors gracefully. Let’s say you have a function called inverse() which simply returns an inverse of the supplied integer. Here are the details of the function.

function inverse($x) {
   return 1/$x;
}

Simple. The problem with this function is when we pass an integer with a value of zero. As you recall in math class, you can’t divide a number by zero. So, we will modify the function by adding an exception handler to it. I will introduce a command called “throw” accompanied by an error message.

function inverse($x) {
    if ($x==0) {
       throw new Exception('Division by zero.');
       echo "I'm zero. Don't let me be the denominator.";
    } else {
       return 1/$x;
    }
}

The modified function now has an “if statement” to check if the integer being passed is zero. If it is, we will invoke the “throw new Exception” command with an error message inside a parenthesis and encapsulated by single quotes. In addition, I’ve added an echo message immediately after the throw command that I will explain later. Now, let’s use our modified inverse() function with the “try” and “catch” commands.

try {
  inverse();
}
catch (Exception $e) {
    echo $e->getMessage();
}

The inverse() function is inside try { } block followed by a catch { } block that simply prints the error message. This is the syntax when using try and catch commands. Every try block must be followed by a catch block. Now back to our function example. Remember the echo “I’m zero. Don’t let me be the denominator” statement? That echo statement never gets executed because when an exception is detected by the try command, it will immediately send the program to the catch block to print the error message.

This is how PHP’s Exception Handling works. If you have comments or questions about PHP Exception Handling, leave me a comment.

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to MySpace Post to Ping.fm Post to Reddit Post to StumbleUpon



One Response to “Understanding PHP Exception Handling”

  1. hey uly., do you understand all this stuff you must be a bright spark,i,m just forgetting stuff all the time ?had stroke [everything seems fast]ecept when i,m walking i,m slow help need with debian language

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes