Home  >  Article  >  Backend Development  >  Exception Handling - PHP Manual Notes

Exception Handling - PHP Manual Notes

WBOY
WBOYOriginal
2016-08-08 09:28:491032browse

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(&#39;Division by zero.&#39;);
    } else {
        return 1 / $x;
    }
}
try {
    echo inverse(5) . &#39;<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(&#39;foo.&#39;);
            } 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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn