Php Exception Handling Methods Summary for friends who need to refer to this article.
When an exception is triggered, it usually occurs:
An error exception handling module similar to other languages is added to PHP5. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. All codes that require exception handling must be placed in the try code block to capture Possible exceptions. Each try must have at least one catch corresponding to it. Multiple catch methods can capture exceptions generated by different classes. When the try code block does not throw an exception or the catch Code cannot be found to match the exception thrown, the PHP code will continue to be executed after the jump to the last catch. Of course, PHP allows another throw exception to be thrown in the catch code block. When an exception is thrown, subsequent Code (the code block where the exception is thrown) will not continue to be executed, PHP will try to find the first catch that can match it. If an Exception is not captured and set_exception_handler () is not used for corresponding processing, PHP will generate a serious error and output the Uncaught Exception... (No exception is captured.
1. hierarchical relationship of exception classes:
The Code is as follows: |
Copy code |
Class NotFoundException extends Exception {} Class InputException extends Exception {} Class DBException extends Exception {} |
2. configure a processor that does not capture exceptions:
The Code is as follows: |
Copy code |
Function exception_uncaught_handler (Exception $ e ){ Header ('content-type: text/html; charset = UTF-8 '); If ($ e instanceof NotFoundException) Exit ($ e-> getMessage ()); Elseif ($ e instanceof DBException) Exit ($ e-> getMessage ()); Else Exit ($ e-> getMessage ()); } Set_exception_handler ('exception _ uncaught_handler ');
|
3. Manually throw a DBException exception in the database connection code, but try... Catch to capture and process the exception. The exception will be customized by the PHP exception processor.
The Code is as follows: |
Copy code |
Prediction_uncaught_handler () function processing: $ This-> resConn = mysql_connect ($ CONFIGS ['db _ host'], $ CONFIGS ['db _ user'], $ CONFIGS ['db _ pwd']); If (false = is_resource ($ this-> resConn )) Throw new DBException ('database connection failed. '. Mysql_error ($ this-> resConn )); |
4. business logic:
If (0! = Strcmp ($ curAlbum-> interest_id, $ it ))
Throw new NotFoundException ('Sorry, the album you accessed does not exist ');
The preceding figure shows how to use a PHP custom exception processor.
Instance
The Code is as follows: |
Copy code |
<? Php Class 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 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:
1. 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.
2. Create the errorMessage () function. If the email address is invalid, this function returns an error message.
3. Execute the "try" code block. Under the first condition, no exception is thrown.
4. Because e-mail contains the string "example", the second condition triggers an exception.
5. 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 Code is as follows: |
Copy code |
<? Php /* */ /* * Conclusion: PHP exceptions can be used in three steps: * Step 1: Define the exception class. If not defined, use the default exception class; * Step 2: throw an exception when an exception occurs, for example, ex1 ($ num2). The exception parameter $ num2 is obtained using the getMessage () of the exception; * Step 3: trigger an exception. Use the try clause to throw new ex1 ($ num) when the condition is met ); * Step 4: catch (ex2 $ e), equivalent to instantiating a defined exception class ex2 is $ e; * * Note: Multiple exceptions can be defined, but only one exception can be triggered. That is to say, only one exception can be caught with catch. */ // ========================= Basic exception class // Create a function that can throw an exception Function num ($ num ){ If ($ num> 1) {// exception throw Condition $ Msg = "the value cannot exceed 1"; // error message Throw new Exception ($ msg); // throw an Exception } Echo "The value is less than 1 ″; } // Trigger an exception in the try code block Try { Num (3 ); Echo "normal execution "; } // Capture exceptions Catch (Exception $ e ){ Echo "error message:". $ e-> getMessage (); // System Method of Exception () to obtain Exception information Echo "error file:". $ e-> getFile (); // System Method of Exception () to obtain the abnormal file name Echo "number of rows:". $ e-> getLine (); // System Method of Exception () to obtain the number of abnormal rows } // ================================================ ====================================== Echo "<br >================================================ ==================================< br> "; // Extended basic exception class Function checkEmail ($ email) {// defines a function that can throw an exception to determine the validity of an EMAIL. If (filter_var ($ email, FILTER_VALIDATE_EMAIL) = false ){ Throw new checkEmailException ($ email); // if an exception is thrown, use EMAIL as the parameter. } Echo "the email is valid "; } Class checkEmailException extends Exception {// defines an extended Exception class Public function errormsg (){ $ Msg = "error cause:". $ this-> getMessage (). "It is not a legal EMAIL address !"; $ Msg. = "error file name:". $ this-> getFile (); $ Msg. = "Number of error rows:". $ this-> getLine (); Echo $ msg; } } $ Email = "email ..... @ Chhua.com "; Try {// trigger an exception CheckEmail ($ email ); } // Capture exceptions Catch (checkEmailException $ e ){ $ E-> errormsg (); } /// ========================================================= Multiple exceptions capture Echo "<br >================================================ ========================< br> "; Class ex1 extends Exception {// defines an Exception class Public function msg (){ $ Msg = "error cause:". $ this-> getMessage (). "greater than 100 <br> "; $ Msg. = "error file:". $ this-> getFile (). "<Br> "; $ Msg. = "error code:". $ this-> getCode (). "<br> "; $ Msg. = "number of rows:". $ this-> getLine (). "<br> "; Echo $ msg; } } Class ex2 extends Exception {// defines an Exception class Public function msg (){ $ Msg = "error cause:". $ this-> getMessage (). "equal to 100 <br> "; $ Msg. = "error file:". $ this-> getFile (). "<Br> "; $ Msg. = "number of rows:". $ this-> getLine (). "<br> "; Echo $ msg; } } $ Num2 = 100; Try { If ($ num2> 100) {// triggered when the condition is met Throw new ex1 ($ num2 ); } If ($ num2 = 100) {// triggered when the condition is met Throw new ex2 ($ num2 ); } } Catch (ex2 $ e) {// catch the exception triggered $ E-> msg (); } Catch (ex1 $ e) {// catch the exception triggered $ E-> msg (); } /* * Conclusion: PHP exceptions can be used in three steps: * Step 1: Define the exception class. If not defined, use the default exception class; * Step 2: throw an exception when an exception occurs, for example, ex1 ($ num2). The exception parameter $ num2 is obtained using the getMessage () of the exception; * Step 3: trigger an exception. Use the try clause to throw new ex1 ($ num) when the condition is met ); * Step 4: catch (ex2 $ e), equivalent to instantiating a defined exception class ex2 is $ e; * * Note: Multiple exceptions can be defined, but only one exception can be triggered. That is to say, only one exception can be caught with catch. */ ?> |