PHP Exception Handling

Source: Internet
Author: User
Tags php exception handling

Exception Handling (also known as error handling) provides a way to handle errors or exceptions that occur when the program is running.

Exception Handling is usually taken to prevent unknown errors. The advantage of exception handling is that you don't have to worry about all kinds of errors, which provides a very effective way to handle a certain type of errors, greatly improving programming efficiency. 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

PHP 5 provides a new object-oriented error handling method. You can use try, throw, and catch exceptions. That is to say, use try to check whether a throw exception is thrown. if an exception is thrown (throw), use catch to catch the exception.

A try must have at least one catch corresponding to it. Multiple catch clauses can be defined to capture different objects. PHP will execute the catch in the defined sequence until the last catch is completed. In these catch operations, a new exception can be thrown.

1. Abnormal use
When an exception is thrown, the subsequent code will not continue to be executed, and PHP will try to find the matching "catch" code block. If an exception is not captured and set_exception_handler () is not used for corresponding processing, PHP will generate a serious error, and the output fails to catch the Exception (Uncaught Exception ...).

Throw an exception but does not capture it:


<? Php
Ini_set ('display _ errors ', 'on ');
Error_reporting (E_ALL &~ E_WARNING );
$ Error = 'ways throw this error ';
Throw new Exception ($ error );
// Continue execution
Echo 'Hello world ';
?>
The above code will get a fatal error like this:

Fatal error: Uncaught exception 'exception' with message 'always throw this error' in E: \ sngrep \ index. php on line 5
Exception: Always throw this error in E: \ sngrep \ index. php on line 5
Call Stack:
0.0005 330680 1. {main} () E: \ sngrep \ index. php: 0
2. Try, throw, and catch

To avoid the above fatal error, you can use try catch to catch it.
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.
Throw an exception and capture it. You can continue to execute the following code:

<? Php
Try {
$ Error = 'ways throw this error ';
Throw new Exception ($ error );
 
// From here on, the code in the tra code block will not be executed
Echo 'never executed ';
 
} Catch (Exception $ e ){
Echo 'caught exception: ', $ e-> getMessage (),' <br> ';
}
 
// Continue execution
Echo 'Hello world ';
?>

In the "try" code block detection, the "throw" exception is not thrown. An exception is thrown here.
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.
To follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors.


3. Extended PHP built-in exception handling class
You can use a custom exception handling class to extend the PHP built-in exception handling class. The following code illustrates which attributes and methods are accessible and inherited in the built-in exception handling class. (Note: The following code only describes the structure of the built-in exception handling class. It is not a practical usable code .)


<? Php
Class Exception
{
Protected $ message = 'unknown exception'; // exception information
Protected $ code = 0; // custom Exception code
Protected $ file; // file name with an exception
Protected $ line; // The code line number with an exception
 
Function _ construct ($ message = null, $ code = 0 );
 
Final function getMessage (); // returns exception information
Final function getCode (); // returns the Exception Code
Final function getFile (); // returns the file name with an exception
Final function getLine (); // return the code line number in which an exception occurs.
Final function getTrace (); // backtrace () array www.2cto.com
Final function getTraceAsString (); // getTrace () information formatted as a string
 
/* Methods that can be reloaded */
Function _ toString (); // output string
}
If you want to use a custom class to extend the built-in exception handling class and redefine the constructor, we recommend that you call parent :__ construct () at the same time to check whether all variables have been assigned values. When an object needs to output a string, you can reload _ toString () and customize the output style.

Build a custom exception handling class:

<? Php
 
/**
*
* Custom exception handling class
*/
 
Class MyException extends Exception
{
// Redefine the constructor to make the message a required attribute
Public function _ construct ($ message, $ code = 0 ){
// Custom code
 
// Make sure all variables are correctly assigned values
Parent: :__ construct ($ message, $ code );
}
 
// Customize the output style of the string */
Public function _ toString (){
Return _ CLASS _. ": [{$ this-> code}]: {$ this-> message} \ n ";
}
 
Public function customFunction (){
Echo "A Custom function for this type of exception \ n ";
}
}
// Example 1: a custom exception is thrown, but no default exception exists.
Echo 'example 1', '<br> ';
Try {
// Throw a custom exception
Throw new MyException ('1 is an invalid parameter ', 5 );
} Catch (MyException $ e) {// catch an exception
Echo "Caught my exception \ n", $ e;
$ E-> customFunction ();
} Catch (Exception $ e) {// ignored
Echo "Caught Default Exception \ n", $ e;
}
// Execute subsequent Code
// Example 2: Throw the default exception but no custom exception
Echo '<br>', 'example 2: ',' <br> ';
Try {
// Throw the default exception
Throw new Exception ('2 isnt allowed as a parameter ', 6 );
} Catch (MyException $ e) {// The exception type cannot be matched and is ignored.
Echo "Caught my exception \ n", $ e;
$ E-> customFunction ();
} Catch (Exception $ e) {// catch an Exception
Echo "Caught Default Exception \ n", $ e;
}
// Execute subsequent Code
// Example 3: throw a custom exception and capture it using the default exception class Object
Echo '<br>', 'example 3: ',' <br> ';
Try {
// Throw a custom exception
Throw new MyException ('3 isnt allowed as a parameter ', 6 );
} Catch (Exception $ e) {// catch an Exception
Echo "Default Exception caught \ n", $ e;
}
 
// Execute subsequent Code
// Example 4
Echo '<br>', 'example 4: ',' <br> ';
Try {
Echo 'no exception ';
} Catch (Exception $ e) {// no Exception, ignored
Echo "Default Exception caught \ n", $ e;
}
 
// Execute subsequent Code
The MyException 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. We can use methods of the exception class, such as getLine (), getFile (), and getMessage ().
4. nested Exception Handling

If an exception in the internal "try" code block is not caught, it searches for the catch code block at the external level to capture the exception.

Try {
Try {
Throw new MyException ('foo! ');
} Catch (MyException $ e ){
/* Re-Throw the rethrow it */
$ E-> customFunction ();
Throw $ e;

}
} Catch (Exception $ e ){
Var_dump ($ e-> getMessage ());
}

5. Set Top-Level Exception Handler)
The set_exception_handler () function can be used to process all user-defined functions without capturing exceptions.


<? Php
Function myException ($ exception)
{
Echo "<B> Exception: </B>", $ exception-> getMessage ();
}
 
Set_exception_handler ('myexception ');
Throw new Exception ('uncaught Exception occurred ');
Output result:

Exception: Uncaught Exception occurred

6. 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; otherwise, the program stops running.


From program life, guisu Column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.