PHP exception handling
Exceptions are used to change the normal flow of the script when a specified error occurs.
What is an exception
PHP 5 provides a new object-oriented error handling method.
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.
When an exception is triggered, what usually happens is:
• The current code state is saved
• Code execution is switched to a 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
We will show different Error handling methods:
• Basic use of exceptions
• Create custom exception handlers
• Multiple exceptions
• Rethrow exceptions
• 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" will be output. wrong information.
Let's try throwing an exception without catching it:
<?php // 创建一个有异常处理的函数 function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } // 触发异常 checkNum(2); ?>
The above code will get an error similar to this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below'
in /www/php/test/test.php:7 Stack trace: #0 /www/php/test/test.php( 13): checkNum(2) #1 {main} thrown
in /www/php/test/test.php on line 7
Try, throw and catch
To avoid the errors seen in the above example, we need to create appropriate code to handle exceptions.
Appropriate exception handling code should include:
1. Try - The function that uses the exception 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.
2. Throw - specifies how to trigger exceptions. Each "throw" must correspond to at least one "catch".
3. Catch - The "catch" code block will catch the exception and create an object containing the exception information.
Let us trigger an exception:
<?php // 创建一个有异常处理的函数 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 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 the properties and methods from the old class, and we can use the exception class methods, such as getLine(), getFile(), and getMessage().
Explanation of examples:
The above code throws an exception and catches it through a custom exception class:
1. 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.
2. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
3. The $email variable is set to an illegal e-mail address string.
4. Execute the "try" code block and throw an exception because the e-mail address is invalid.
5. The "catch" code block catches the exception and displays the 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(); } ?>
Example explanation:
The above code tests two conditions. If any of them If a condition is not true, an exception is thrown:
1. The customException() class is created as an extension of the old exception class. This way it inherits all properties and methods of the old exception class.
2. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".
4. Execute the "try" code block, and no exception will be thrown under the first condition.
5. Since the e-mail contains the string "example", the second condition will trigger an exception.
6. 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 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 more 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(); } ?>
Explanation of examples:
The above code detects that Whether the email address contains the string "example". If so, throw the exception again:
1. 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.
2. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".
4. The "try" block contains another "try" block so that the exception can be thrown again.
5. Because the e-mail contains the string "example", an exception is triggered.
6. The "catch" code block catches the exception and rethrows "customException".
7. "customException" is caught and an error message is displayed.
If the exception is not caught in the current "try" block, it will look for a catch block at a higher level.
Set the top-level exception handler
The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.
<?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>
The output of the above code is as follows:
Exception: Uncaught Exception occurred
In the above code, there is no "catch" code block, triggering the top-level exception handler instead. This function should be used to catch all uncaught exceptions.
Exception rules
1. Code that requires exception handling should be placed in a try code block to capture potential abnormal.
2. Each try or throw code block must have at least one corresponding catch code block.
3. Use multiple catch code blocks to catch different types of exceptions.
4. Exceptions can be thrown (thrown again) in the catch block within the try block.
In short: if an exception is thrown, you must catch it.