Exception handling in PHP development basic tutorial
1. What is an exception?
Exceptions are used to alter the normal flow of a script when a specified error occurs.
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 Predefined (custom) exception handler functions
Depending on the situation, the handler may restart code execution from the saved code state, terminate script execution, or retrieve additional code from within the code. Continue executing the script at location
We will show different error handling methods:
Basic use of exceptions
-
Create a custom exception handler
Multiple exceptions
Rethrow the exception
-
Set the top-level exception handler
Note: Exceptions should only be used in error situations and should not be used to jump to another part of the code at a specified point. a location.
##2. 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 set_exception_handler() is not used for corresponding processing, a serious error (fatal error) will occur and an "Uncaught Exception" error will be output. information. Let's try throwing an exception without catching it: The code is as follows:<?php // 创建一个有异常处理的函数 function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } // 触发异常 checkNum(2); ?>You will get an output similar to this:
3. Try, throw and catch
To avoid the errors in the above example, we need to create appropriate code to handle exceptions. Appropriate exception handling code should include:- Try - Functions that use exceptions should be located within a "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 catches the exception and creates an object containing the exception information.
<?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 output is as shown on the right
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.
4. 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 to create the exception class:
The code is as follows
<?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(); } ?>
The output result is shown in the picture on the right
This new class is the old exception class A copy of , 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 the 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 the exception and displays the error message
5. 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:
The code is as follows
<?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 test Two conditions are specified. 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 the 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.
Since the e-mail contains the string "example", the second condition will trigger an exception.
The "catch" block catches the exception and displays the appropriate error message.
If the customException class throws an exception, but does not catch the customException, but only catches the base exception, handle the exception there.
6. Rethrow exceptions
Sometimes, when an exception is thrown, you may want to use it differently than the standard way to process it. 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:
The code is as follows
<?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(); } ?>
The output is shown on the right
Explanation of examples:
The above code detects whether the email address contains the string "example". If so, throw the exception 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", an 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 on a higher level.
7. Set the top-level exception handler
The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.
The code is as follows
<?php function myException($exception) { echo "<b>Exception:</b> " , $exception->getMessage(); } set_exception_handler('myException'); throw new Exception('Uncaught Exception occurred'); ?>
The output is shown on the right
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.
8. Exception rules
Code that requires exception handling should be placed in the try code block within to catch potential exceptions.
Each try or throw block must have at least one corresponding catch block.
Use multiple catch code blocks to catch different kinds 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.