Exception handling for beginners in PHP
Exceptions are used to change the normal flow of the script when a specified error occurs.
1. What is an exception
Exception handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception.
2. When an exception is triggered, what usually happens is:
The current code state is saved
Code execution is switched to the predefined (custom) exception handler Function
Depending on the situation, the processor may restart code execution from the saved code state, terminate script execution, or continue script execution from another location in the code
3. We will show different error handling methods:
Basic use of exceptions
Creating custom exception handlers
Multiple exceptions
Re Throw exception
Set top-level exception handler
☆Note: Exceptions should only be used in error situations and should not be used to jump to another location in the code at a specified point
Basic use of exceptions:
When an exception is thrown, the subsequent code will not continue to execute, and PHP will try to find a matching "catch" code block.
If the exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then a serious error (fatal error) will occur and "Uncaught Exception" (uncaught exception) will be output. wrong information.
Let's try throwing an exception without catching it
<?php
// Create a function with exception handling
function checkNum($number) {
($ Number & GT; 1) {
Throw New Exception ("Value Must be 1 or Below");
}
Return true; ##checkNum(2);
?>
The above code will get an error similar to this:
Try, throw and catch
To avoid the errors in the above example, we need to create the appropriate code to handle exceptions.
Appropriate exception handling code should include: Try - Functions that use exceptions should be located within the "try" code block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown. Throw - specifies how to trigger exceptions. 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 us trigger an exception
<?php header("Content-type: text/html; charset=utf-8");//设置编码 // 创建一个有异常处理的函数 function checkNum($number){ if($number>1){ throw new Exception("变量值必须小于等于 1"); } return true; } // 在 try 块 触发异常 try{ checkNum(2); // 如果抛出异常,以下文本不会输出 echo '如果输出该内容,说明 $number 变量'; } // 捕获异常 catch(Exception $e){ echo 'Message: ' .$e->getMessage(); } ?>
The above code will get an error similar to this:
Message: The variable value must be less than or equal to 1
Explanation of examples:
The above code throws an exception and catches it:
Create the 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 is thrown.
The "catch" code block receives the exception and creates an object ($e) containing the exception information.
Output the error message from this exception by calling $e->getMessage() from this exception object.
However, in order to follow the principle of "each throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors.
Create a custom Exception class
Creating a custom exception handler is very simple. We simply created a specialized class whose functions can be called when an exception occurs in PHP. This class must be an extension of the exception class.
This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it.
We start by creating the exception class:
<?php class customException extends Exception { public function errorMessage() { // 错误信息 $errorMsg = '错误行号 '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> 不是一个合法的 E-Mail 地址'; return $errorMsg; } } $email = "someone@example...com"; try { // 检测邮箱 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { // 如果是个不合法的邮箱地址,抛出异常 throw new customException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
This new class is a copy of the old exception class, plus the errorMessage() function. Just because it is a copy of the old class, it inherits properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage().
Explanation of examples:
The above code throws an exception and catches it through a custom exception class:
The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to an illegal e-mail address string.
Execute the "try" code block and throw an exception because the e-mail address is illegal.
The "catch" code block catches exceptions and displays an error message.
Multiple exceptions
You can use multiple exceptions for a script to detect multiple situations.
You can use multiple if..else code blocks, or a switch code block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:
<?php class customException extends Exception { public function errorMessage() { // 错误信息 $errorMsg = '错误行号 '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> 不是一个合法的 E-Mail 地址'; return $errorMsg; } } $email = "someone@example.com"; try { // 检测邮箱 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { // 如果是个不合法的邮箱地址,抛出异常 throw new customException($email); } // 检测 "example" 是否在邮箱地址中 if(strpos($email, "example") !== FALSE) { throw new Exception("$email 是 example 邮箱"); } } catch (customException $e) { echo $e->errorMessage(); } catch(Exception $e) { echo $e->getMessage(); } ?>
Explanation of examples:
The above code tests two If any of the conditions is not true, an exception is thrown:
The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to a string that is a valid e-mail address but contains the string "example".
Execute the "try" code block, and no exception will be thrown under the first condition.
Because the e-mail contains the string "example", the second condition will trigger an exception.
The "catch" code block will catch the exception and display the appropriate error message.
If the customException class throws an exception, but the customException is not caught, and only the base exception is caught, the exception is handled there.
Rethrow the exception
Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. The exception can be thrown again in a "catch" block.
The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message:
<?php class customException extends Exception { public function errorMessage() { // 错误信息 $errorMsg = $this->getMessage().' 不是一个合法的 E-Mail 地址。'; return $errorMsg; } } $email = "someone@example.com"; try { try { // 检测 "example" 是否在邮箱地址中 if(strpos($email, "example") !== FALSE) { // 如果是个不合法的邮箱地址,抛出异常 throw new Exception($email); } } catch(Exception $e) { // 重新抛出异常 throw new customException($email); } } catch (customException $e) { // 显示自定义信息 echo $e->errorMessage(); } ?>
Example explanation:
The above code detects whether the email address contains the string "example". If so, the exception is thrown again: The
customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to a string that is a valid e-mail address but contains the string "example".
The "try" block contains another "try" block so that the exception can be thrown again.
Because the e-mail contains the string "example", the exception is triggered.
The "catch" code block catches the exception and rethrows "customException".
Catch "customException" and display an error message.
If the exception is not caught in the current "try" block, it will look for a catch block at a higher level.
Exception rules
Code that requires exception handling should be placed in a try code block to catch potential exceptions.
Each try or throw code block must have at least one corresponding catch code block.
Use multiple catch code blocks to catch different types of exceptions.
Exceptions can be thrown (thrown again) in a catch block within a try block.
In short: if an exception is thrown, you must catch it.