ArticleDirectory
- Try, throw, and catch
- Example:
- Example:
- Example:
- Example:
Introduction: This is a detailed page for PHP Exception Handling. It introduces related knowledge, skills, experience, and some PHP source code.
Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 361154 'rolling = 'no'> 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:
- CurrentCodeStatus 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:
<? PHP // 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.
ProcessingProgramIt 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:
<? PHP // create a function that can throw an exception. Function checknum ($ number) {if ($ number> 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:
<? Phpclass customexception extends exception {public function errormessage () {// error message $ errormsg = 'error on line '. $ this-> Getline (). 'in '. $ this-> GetFile (). ': <B> '. $ this-> getmessage (). '</B> is not a valid e-mail address'; return $ errormsg ;}}$ email = "Someone @ example...com "; try {// check if (filter_var ($ email, filter_validate_email) === false) {// throw Exception If email is not valid t Hrow 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. 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:
<? Phpclass customexception extends exception {public function errormessage () {// error message $ errormsg = 'error on line '. $ this-> Getline (). 'in '. $ this-> GetFile (). ': <B> '. $ this-> getmessage (). '</B> is not a valid e-mail address'; return $ errormsg; }}$ email = "someone@example.com "; try {// check if (filter_var ($ email, filter_validate_email) === false) {// throw Exception If email is not valid throw new Cu Stomexception ($ 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:
<? Phpclass customexception extends exception {public function errormessage () {// 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 custom 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.
<? Phpfunction myexception ($ exception) {echo "<B> exception: </B>", $ 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.
From: http://www.w3school.com.cn/php/php_exception.asp
Love J2EE follow Java Michael Jackson video station JSON online tools
Http://biancheng.dnbcw.info/php/361154.html pageno: 1.