PHP

Exceptions[]

Exceptions are a powerful validation tool in PHP.

Why use Exceptions[]

There are many reasons why to use exceptions.

Examples include:

   - Function Parameter Validation
   - Input/Output Validation
   - An alternate form of error reporting

An Example[]

Here's an example to get started; I'll go from here:

function divide( $number_1, $number_2 ) {

   // Surroubd possible Exception throwing in a try… block
   try {
       if ( !isint( $number_1 ) || !isint( $number_2 ) {
           // Throw a new Exception using the given message and code
           throw new Exception("number_1 and number_2 must be integers", 1);
       }
       else if ( $number_2 === 0 ) {
           // Throw DivisionByZero Exception
           throw new Exception("Division by zero", 2);
       }
       else if ($number_1 === 0 ) {
           // Return zero
           return 0;
       }
       else {
           // Return the result of division.
           return $number_1 / $number_2;
       }
   }
   // If an exception is thrown, we jump here.
   catch($e) {
       // Note that $e is the Exception object itself.
       // Tell the user about the Exception and return 0.
       print("$e->getCode: $e->getMessage");
       echo "\n";
       print("Please contact an admin if you need more help.\n\n");
       return 0;
   }

}

An Explanation[]

The above code illustrates a good example of when you would use Exceptions.

First, you surround the code you want to test with a try block.

Next, you use if statements to validate code, etc. and if a problem occurs, you use the throw keyword followed by the new keyword, an Exception Class (like Exception or ErrorException), and an open parenthesis.

The first parameter to the constructor is the Exception message, try to be as helpful as youh can while fitting the message in under 80 characters. Unless you're doing simple scription, you will also want to assign an exception code to it. This code is the second parameter.

The third step is to close the try block and create a catch( Exception_Class $exception_variable) block with the exception handling inside. Use$exception_variable, which by the way is arbituary, to refer to the thrown Exception Object.

Finally, starting with PHP 5.5 (i believe), after the Catch blocks, you can add a finally block which is always run unless a fatal error occurs, or the function returns.