Home > Article > Backend Development > Exception Handling - PHP Manual Notes
Exceptions generated in PHP code can be thrown by the throw
statement and captured by the catch
statement. Code that requires exception handling must be placed within the try
code block, and each try
must have at least one corresponding catch
. When an exception is thrown, the code following the code block will not continue to execute. At this time, PHP will try to find the first matching catch
. Of course, PHP allows throw
exceptions to be thrown again within a catch
code block. If an exception is not caught and handled accordingly using set_exception_handler()
, PHP will generate a fatal error.
Here is an example of exception usage.
<code><?php function inverse($x) { if(!$x) { throw new Exception('Division by zero.'); } else { return 1 / $x; } } try { echo inverse(5) . '<br>'; echo inverse(0) . '<br>'; } catch(Exception $e) { echo 'Caught exception: ' . $e->getMessage() . '<br>'; } echo 'hello';</code>
There is also an example of exception nesting.
<code><?php class MyException extends Exception {} class Test { public function testing() { try { try { throw new MyException('foo.'); } catch(MyException $e) { throw $e; } } catch(Exception $e) { var_dump($e->getMessage()); } } } $foo = new Test; $foo->testing();</code>
Users can extend PHP's built-in exception handling classes with custom exception handling classes.
(Full text ends)
The above introduces the exception handling - PHP manual notes, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.