Exception is used to change the normal process of the script when a specified error occurs. What is an exception? PHP5 provides a new object-oriented error handling method. Exception handling is used to change the normal process of the script when a specified error (exception) occurs. This is called an exception. When an exception is triggered, it usually occurs: the current code is like "> <LINKhref =" http: // www. php10
Exception is used to change the normal process 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 process of the script when a specified error (exception) occurs. This is called an exception.
When an exception is triggered, it usually occurs:
The current code status is saved.
Code execution is switched to a predefined exception processor function
Depending on the situation, the processor may re-execute the code from the saved code status, terminate the script execution, or continue to execute the script from another position in the code
We will display different error handling methods:
Basic usage of exceptions
Create a custom exception processor
Multiple exceptions
Throw an exception again.
Set the top-level exception processor
Basic usage of exceptions
When an exception is thrown, the subsequent code will not be executed, and PHP will try to find the matching "catch" code block.
If the exception is not captured and set_exception_handler () is not used for corresponding processing, a serious (fatal) error will occur ), and output the "Uncaught Exception" (No Exception is caught) error message.
Let's try to throw an exception without capturing it:
// Create function with an exceptionfunction
CheckNum ($ number ){
If ($ number> 1 ){
Throw new Exception ("Value must be 1 or below ");
} Return true;
}
// Trigger
ExceptioncheckNum (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 C: \ webfolder \ test. php: 6 Stack trace: #0 C: \ webfolder \ test. php (12): checkNum (28) #1 {main} thrown in C: \ webfolder \ test. php on line 6
Try, throw, and catch
To avoid errors in the above example, we need to create appropriate code to handle exceptions.
The processing process should include:
Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the code continues as usual. However, if an exception is triggered, an exception is thrown.
Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The Catch-"catch" code block captures exceptions and creates an object containing exception information.
Let's trigger an exception:
1) {throw new Exception ("Value must be 1 or below");} return true;} // trigger an Exception in the "try" code block try {checkNum (2 ); // If the exception is thrown, this text will not be shown echo 'If you see this, the number is 1 or below';} // catch an Exception catch (exception $ e) {echo 'message :'. $ e-> getMessage () ;}?>
The above code will get an error similar to this:
Message: Value must be 1 or below
Example:
The above code throws an exception and captures it:
Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown.
Call the checkNum () function in the "try" code block.
An exception in the checkNum () function is thrown.
The "catch" code block receives the exception and creates an object ($ e) containing the exception information ).
Call $ e-> getMessage () from this exception object to output error messages from this exception.
However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors.
Create a custom Exception class
It is very easy to create a custom exception handler. We have simply created a special class. When an exception occurs in PHP, we can call its function. This class must be an extension of the exception class.
This custom exception class inherits all attributes of the PHP exception class. you can add custom functions to it.
Let's start to create the exception class:
Class customException extends Exception {
Public function errorMessage (){
// Error message
$ ErrorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ().':'. $ This-> getMessage ().'Is not a valid E-Mail address '; return $ errorMsg;
}
}
$ Email = "someone @ example...com"; try {
// Check if
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE ){
// Throw exception if email is not valid throw
New customException ($ email );
}
} Catch (customException $ e)
{
// Display M message
Echo $ e-> errorMessage ();
}?>
This new class is a copy of the old exception class, plus the errorMessage () function. Because it is a copy of the old class, it inherits attributes and methods from the old class. we can use methods of the exception class, such as getLine () and getFile () and getMessage ().
Example:
The above code throws an exception and captures it through a custom exception class:
The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Set the $ email variable to an invalid email address string.
Execute the "try" code block. An exception is thrown because the email address is invalid.
The "catch" code block captures exceptions and displays error messages.
Multiple exceptions
Multiple exceptions can be used for a script to detect multiple cases.
You can use multiple if. else code blocks, a switch code block, or nested exceptions. These exceptions can use different exception classes and return different error messages:
Class customException extends Exception {public function errorMessage (){
// Error
Message $ errorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ().':'. $ This-> getMessage ().'Is not a valid E-Mail address ';
Return $ errorMsg;
}
}
$ Email = "someone@example.com"; try {
// Check if
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE ){
// Throw exception if email is not valid throw new
CustomException ($ email );
}
// Check for "example" in mail address
If (strpos ($ email, "example ")! = FALSE) {throw new Exception ("$ email is an example e-mail") ;}} catch (customException $ e) {echo $ e-> errorMessage ();} catch (Exception $ e) {echo $ e-> getMessage () ;}?>
Example:
The code above tests two conditions. if any condition is not true, an exception is thrown:
The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Execute the "try" code block. under the first condition, no exception is thrown.
Because e-mail contains the string "example", the second condition triggers an exception.
The "catch" code block captures exceptions and displays appropriate error messages.
If the base mexception is not captured and the base exception is captured tightly, the exception is handled there.
Throw an exception again.
Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" code block.
The script should hide system errors from users. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can throw an exception with user-friendly messages again:
// Error message
$ ErrorMsg = $ this-> getMessage (). 'is not a valid E-Mail address.'; return $ errorMsg; }}$ email = "someone@example.com"; try {
// Check for "example" in mail address
If (strpos ($ email, "example ")! = FALSE ){
// Throw exception if email is not valid throw new
Exception ($ email) ;}} catch (Exception $ e ){
// Re-throw exception throw new
CustomException ($ email) ;}} catch (customException $ e ){
// Display M message
Echo $ e-> errorMessage () ;}?>
Example:
The code above checks whether the email address contains the string "example ". If yes, an exception is thrown again:
The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Set the $ email variable to a valid email address, but it contains the string "example ".
The "try" code block contains another "try" code block, so that an exception can be thrown again.
An exception is triggered because e-mail contains the string "example.
"Catch" captures this exception and throws "customException" again ".
Capture "customException" and display an error message.
If an exception is not caught in its current "try" code block, it looks for the catch code block at a higher level.
Top Level Exception Handler)
The set_exception_handler () function can be used to process all user-defined functions without capturing exceptions.
Function myException ($ exception ){
Echo"Exception:", $ Exception-> getMessage ();
}
Set_exception_handler ('myexception ');
Throw new Exception ('uncaught Exception occurred');?>
The output of the above code should be similar to the following:
Exception: Uncaught Exception occurred
In the above code, the "catch" code block does not exist, but triggers the exception handler at the top layer. This function should be used to capture all exceptions that are not captured.
Abnormal rules
Code that requires exception handling should be placed in the try code block to capture potential exceptions.
Each try or throw code block must have at least one catch code block.
Multiple catch code blocks can capture different types of exceptions.
You can throw a (re-thrown) exception again in the catch code block in the try code block.
In short: if an exception is thrown, it must be caught.