| PHP Exceptions |
|
|
|
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exeptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block. When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler(). Example 1: Throwing an exception function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } else return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; }catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Continue execution echo 'Hello World'; ?> Occasionally, the functions do not support exceptions. Instead of seeing the PHP warning about the file not being found, the following can be used: Example 2: Executing functions that don't support exceptions //-- Try to open the file --// $query_string = "http://www.example.com/file.html"; try{ $data = @file($query_string); if($data == FALSE){ throw new Exception('Remote file was not found'); }else{ $html = implode('', $data); } }catch(Exception $e){ print $e->getMessage(); return; } The warning is supressed with "@" and since the size of $data is zero, an exception is thrown. |



