Home > Article > Backend Development > Simple usage of Try, throw and catch in PHP_PHP Tutorial
This article briefly records the usage of Try, throw and catch in PHP. I will do a detailed analysis later when I have time.
Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if the exception is triggered, a
will be thrownException.
Throw - This specifies how to trigger the exception. Each "throw" must correspond to at least one "catch"
Catch - The "catch" code block will catch the exception and create an object containing the exception information
Let’s trigger an exception:
<?php //创建可抛出一个异常的函数 function checkNum($number){ if($number>1){ throw new Exception("Value must be 1 or below"); } return true; } //在 "try" 代码块中触发异常 try{ checkNum(2); //捕获异常 }catch(Exception $e){ echo 'Message: ' .$e->getMessage(); }
The above code will get an error similar to this:
Message: Value must be 1 or below
Explanation of examples:
The above code throws an exception and catches it:
Create checkNum() function. It detects whether the number is greater than 1. If so, throw an exception.
Call the checkNum() function in the "try" code block.
Exception in checkNum() function was thrown
The "catch" code block receives the exception and creates an object ($e) containing the exception information.
By calling $e->getMessage() from this exception object, the error message from the exception is output, however, in order to comply with "Each throw must correspond to one
Based on the catch principle, a top-level exception handler can be set up to handle missed errors.