Exceptions are used to change the normal flow of the script when a specified error occurs.
What is the 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 the predefined (self Definition)Exception handler function
· Depending on the situation, the handler 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
· Creating custom exception handlers
· Multiple Exceptions
· Rethrow exceptions
· Set top-level exception handler
Comments: Exceptions should only be used in error situations and should not Used to jump to another location in the code at a specified point.
Basic use of exceptions
##When an exception is thrown, the following 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) error message. 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 D:\WWW\11.php:7 Stack trace: #0 D:\WWW\11.php(13): checkNum(2) #1 {main} thrown in D:\WWW\11.php on line 7
Try, throw and catch
#To avoid the error in the above example, we need to create appropriate code to handle exceptions .
Appropriate exception handling code should include:
1. 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.
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 exception information.
##Example
Let’s 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 like this:
Message: The variable value must be less than or equal to 1
##Comment: throw new Exception Explicitly throw an exception
The above code throws an exception and catches it:
1 . Create checkNum() function. It detects whether the number is greater than 1. If so, throw an exception.
2. Call the checkNum() function in the "try" code block.
3. The exception in the checkNum() function is thrown.
4. The catch" code block receives the exception and creates an object ($e) containing the exception information.
5. By calling $e->getMessage from this exception object (), output the error message from the exception.
However, in order to follow the principle of "each throw must correspond to a catch", a top-level exception handler can be set up 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 are 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 header("Content-type:text/html;charset=utf-8"); 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 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().
getLine(): Get the line number of the code in the file where the exception occurred
getFile(): Get the name of the program file where the exception occurred
getMessage(): Get the exception message content
Explanation of examples:
The above code throws an exception and catches it through a custom exception class:
1. The customException() class is used as the old exception Created as an extension of the 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 an illegal e-mail address string.
4. Execute the "try" code block and throw an exception because the e-mail address is illegal.
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 header("Content-type:text/html;charset=utf-8"); 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 conditions. If any of the conditions is not true, an exception is thrown:
1. The customException() class is used as the old exception class Created by an extension. 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 exception When thrown, you may want to handle it differently than the standard. 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 header("Content-type:text/html;charset=utf-8"); 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(); } ?>
The above code detects whether the email address contains the string "example". If so, throw the exception again: 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. The "try" code block contains another "try" code 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. 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. Set top-level exception handler ##set_exception_handler## The #() function sets a user-defined function that handles all uncaught exceptions. The output of the above code is as follows: #In the above code, there is no "catch" code block, but the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions. 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 the catch code block within the try code block. In short: if an exception is thrown, you must catch it. <?php
header("Content-type:text/html;charset=utf-8");
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
Exception: Uncaught Exception occurred