Home >Backend Development >PHP Tutorial >PHP simple exception handling and nested exceptions
PHP 5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by throw statements and caught by catch statements. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Each try must have at least one corresponding catch. Use multiple catches to catch exceptions generated by different classes. When the try code block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code will continue execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.
When an exception is thrown, the subsequent code (Translator's Note: refers to the code block when the exception is thrown) will not continue to execute, and PHP will try to find the first matching catch . If an exception is not caught, and there is no need to use set_exception_handler() for corresponding processing, then PHP will generate a serious error and output an Uncaught Exception... (uncaught exception) prompt message.
Note HP internal functions mainly use error reporting, only modern object-oriented extensions use exceptions. But errors can be easily converted into exceptions through ErrorException.
PHP Standard Library (SPL) provides many built-in exception classes.
Example #1 throws an exception
<?php 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'; ?>
The above routine will output:
0.2
Caught exception: Division by zero.
Hello World
Example #2 Nested exception
<?php class MyException extends Exception { } class Test { public function testing() { try { try { throw new MyException('foo!'); } catch (MyException $e) { /* rethrow it */ throw $e; } } catch (Exception $e) { var_dump($e->getMessage()); } } } $foo = new Test; $foo->testing(); ?>
The above routine will output :
string(4) "foo!"