PHP Try, throw, and catch simple usage
This article briefly records the usage of Try, throw, and catch in php, and then provides a detailed explanation later.
Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the Code continues as usual. However, if an exception is triggered,
Exception.
Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The Catch-"catch" code block captures exceptions and creates an object containing exception information.
Let's trigger an exception:
<? Php // create a function that can throw an Exception. function checkNum ($ number) {if ($ number> 1) {throw new Exception ("Value must be 1 or below ");} return true;} // trigger an Exception in the "try" code block try {checkNum (2); // catch an Exception} catch (Exception $ e) {echo 'message :'. $ e-> getMessage ();}
The above code will get an error similar to this:
Message: Value must be 1 or below
Example:
The above code throws an exception and captures it:
Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown.
Call the checkNum () function in the "try" code block.
An exception in the checkNum () function is thrown.
The "catch" code block receives the exception and creates an object ($ e) containing the exception information ).
Call $ e-> getMessage () from this exception object to output the error message from this exception.
Catch principle. You can set a top-level exception processor to handle missed errors.
Articles you may be interested in
- Simple Example of php getting webpage content through socket
- Php prompts PHP Warning: date (): It is not safe to rely on the... solution to the error
- Usage of several keywords such as $ this, static, final, const, and self in php
- PhpMyAdmin Cannot start session without errors error Solution
- Install and configure memcache in windows
- SMTP Error cocould not connect to SMTP host. send fail
- Comparison of file_get_contents with curl in PHP
- Principles and tutorials of PHP connection and Memcached manipulation