PHP try, throw and catch
Try, throw, and catch
- 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:
function Checknum ($number)
{
if ($number >1) {
throw new Exception ("Value must be 1 or below");
}
return true;
}
Try {
Checknum (2);
If the exception is a thrown, this text won't be shown Echo's If you see this , the number is 1 or below '; }
Catching exceptions
catch (Exception $e)
{ echo ' Message: '. $e->getmessage ();
The above code will get an error like this:
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.
PHP try, throw and catch