Basic use of exceptions
When the exception is thrown, the subsequent code does not continue, and PHP tries to find a matching "catch" block.
If the exception is not captured and does not use Set_exception_handler () for appropriate processing, a serious error (fatal error) will occur, and an error message "Uncaught exception" (uncaught exception) is output.
Let's try to throw an exception without catching it:
<?php//create function with an exceptionfunction checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; }//trigger exceptioncheckNum(2);?>
The above code will get an error like this:
PHP Fatal error: ‘Exception‘ with message ‘Value must be 1 or below‘ in /home/wangkongming/babytree/test/php/php_ob/3.php:7Stack trace:#0 /home/wangkongming/babytree/test/php/php_ob/3.php(12): checkNum(2)#1 {main} thrown in /home/wangkongming/babytree/test/php/php_ob/3.php on line 7
Try, throw, and catch
To avoid the error in the above example, we need to create the appropriate code to handle the exception.
The correct processing procedure should include:
Try-the function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown.
Throw-this specifies how the exception is triggered. Each "throw" must correspond to at least one "catch"
Catch-the "catch" code block catches an exception and creates an object that contains the exception information
Let's trigger an exception:
<?phpCreate function with an exceptionfunction checknum ($number) {if ($number >1) {throw new exception (" Value must be 1 or below ");} return true;} //trigger exception try{checknum ( 2); echo "If you see this, the number is 1 or below"; catch (exception $e) {echo ' Message: '. $e, GetMessage ();} ?>
Run the above code:
Message: Value must be 1 or below
Example Explanation:
The above code throws an exception and captures it:
Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown.
Call the Checknum () function in the "Try" code block.
The exception in the Checknum () function is thrown
The catch code block receives the exception and creates an object ($e) that contains the exception information.
Output the error message from this exception by calling $e->getmessage () from this exception object
However, to follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing error.
Exception exception in PHP