Exception handling, also known as Error handling, provides a way to handle errors or exceptions that occur when a handler runs.
Exception handling is usually the action taken to prevent an unknown error from Arising. The advantage of exception handling is that you don't have to work your brains out to think about all kinds of errors, which provides a very effective way to deal with a certain kind of error, which greatly improves the efficiency of programming. When an exception is triggered, it usually occurs:
Current code state is saved
Code execution is switched to the pre-defined exception handler function
Depending on the situation, the processor may start executing the code again from the saved code state, terminating the script execution, or continuing the script from another location in the code
PHP 5 provides a new approach to object-oriented error handling. You can use instrumentation (try), throw (throw), and Catch (catch) exceptions. Even if the throw (throw) exception is detected with a try, the catch is used to catch the exception if an exception is thrown (throw).
A try must have at least one catch corresponding to it. You can capture different objects by defining multiple Catch. PHP executes in the order in which the catch is defined, until the last one is Completed. Within these catch, a new exception can be thrown.
1. Use of exceptions
When an exception is thrown, the subsequent code will not proceed, and PHP will attempt to find a matching "catch" block of Code. If an exception is not captured and is not used with Set_exception_handler (), then PHP will produce a serious error and the output fails to catch the exception (uncaught exception ...) Prompt for Information.
Throws an exception, but does not capture it:
<? PHP Ini_set (' display_errors ', ' on '); error_reporting (e_alle_warning); $error = ' Always throw this error '; Throw New Exception ($error); // Continue execution Echo ' Hello world ';
The above code will get a fatal error like This:
Exception ' Exception ' with the message ' Always throw the This error ' in E:\sngrep\index.php to line 5Exceptionthrow this E Rror in E:\sngrep\index.php on line 5 callStack: 0.0005 330680 1. {main} () e:\sngrep\index.php:0
2. try, throw, and catch to avoid this fatal error, you can use try catch to catch it Out.
The processing handler should include:
Try-the function that uses the exception should be in the "try" code BLOCK. If no exception is triggered, the code will continue to execute as Usual. however, If an exception is triggered, an exception is Thrown.
THROW-THIS specifies how the exception is Triggered. Each "throw" must correspond to at least one "catch"
Catch-the "catch" code block catches an exception and creates an object that contains the exception information
Throws an exception and catches it, you can proceed with the following code:
<?PHPTry { $error= ' Always throw this error '; Throw New Exception($error); //from here, the code within the TRA code block will not be executed Echo' Never executed ';} Catch(Exception $e) { Echo' Caught Exception: ',$e->getmessage (), ' <br> ';}//Continue executionEcho' Hello World ';?>
The "try" code block detects that there are no throws "throw" exceptions, and throws an exception Here.
The catch code block receives the exception and creates an object ($e) that contains the exception Information.
Output the error message from this exception by calling $e->getmessage () from this exception object
To follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing Error.
3. Extended PHP built-in exception handling class
Users can use custom exception handling classes to extend PHP's built-in exception handling Classes. The following code shows which properties and methods are accessible and inheritable in the subclass of the built-in exception-handling class. (note: The following code is only a description of the structure of the built-in exception-handling class, and it is not a meaningful piece of code Available.) )
<?PHPclass Exception{ protected $message= ' Unknown exception ';//Exception Information protected $code= 0;//user-defined Exception Codes protected $file;//the file name of the exception that occurred protected $line;//the line number of the code where the exception occurred function__construct ($message=NULL,$code= 0); Final functionGetMessage ();//Return exception Information Final functionGetCode ();//return Exception Code Final functionGetFile ();//returns the file name of the exception that occurred Final functionGetLine ();//returns the line number of the code where the exception occurred Final functionGettrace ();//backtrace () Array Final functionGettraceasstring ();//Gettrace () information that has been rasterized into a string /*methods that can be overloaded*/ function__tostring ();//A string that can be output}
If you use a custom class to extend the built-in exception-handling class, and you want to redefine the constructor, it is recommended that you call Parent::__construct () at the same time to check that all variables have been assigned Values. You can overload __tostring () and customize the style of the output when the object is about to output a string.
To build a custom exception-handling class:
<?PHP/** * * Customize an exception handling class*/classMyExceptionextends Exception{ //redefine the constructor to make the message a property that must be specified public function__construct ($message,$code= 0) { //Custom Code//make Sure all variables are correctly assignedParent::__construct ($message,$code); } //Custom string Output style * / public function__tostring () {return __class__. ": [{$this->code}]: {$this->message}\n "; } public functioncustomfunction () {Echo"A Custom function for this type of exception\n"; }}//Example 1: throw a custom exception, but no default exceptionEcho' Example 1 ', ' <br> ';Try { //throw a custom exception Throw NewMyException (' 1 is an invalid parameter ', 5);} Catch(myexception$e) {//Catching exceptions Echo"caught my exception\n",$e; $e-customfunction ();} Catch(Exception $e) {//is ignored Echo"caught Default exception\n",$e;}//Execute subsequent code//example 2: throws the default exception but no custom exceptionEcho' <br> ', ' example 2: ', ' <br> ';Try { //throws the default exception Throw New Exception(' 2 isnt allowed as a parameter ', 6);} Catch(myexception$e) {//cannot match the kind of exception that is ignored Echo"caught my exception\n",$e; $e-customfunction ();} Catch(Exception $e) {//Catching exceptions Echo"caught Default exception\n",$e;}//Execute subsequent code//example 3: throw a custom exception, use the default Exception class object to captureEcho' <br> ', ' example 3: ', ' <br> ';Try { //throw a custom exception Throw NewMyException (' 3 isnt allowed as a parameter ', 6);} Catch(Exception $e) {//Catching exceptions Echo"Default Exception caught\n",$e;}//Execute follow-up code//example 4Echo' <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. Thus it inherits all the properties and methods of the old class, and we can use the methods of the exception class, such as GetLine (), getFile (), and GetMessage ().
4. Nesting Exception Handling
If an exception is not caught in the inner "try" code block, it looks for a catch code block on the outer level to Capture.
Try { Try { Throw NewMyException (' foo! '); } Catch(myexception$e) { /*Re-throw rethrow It*/ $e-customfunction (); Throw $e; }} Catch(Exception $e) { Var_dump($e-getMessage ());}
5. Set the top level exception handler (top Exception Handler)
The Set_exception_handler () function sets a user-defined function to handle all uncaught exceptions.
<? PHP function myexception ($exception) {echo$exception-getMessage ();} Set_exception_handler (' myexception '); Throw New Exception (' uncaught Exception occurred ');
Output result: exception:uncaught Exception occurred
6. Rules for exceptions
- The code that requires exception handling should be placed inside a try code block to catch a potential exception.
- Each try or throw code block must have at least one corresponding catch code BLOCK.
- You can use multiple catch blocks to catch different kinds of exceptions.
- You can throw (re-thrown) exceptions again in a catch code block within a try code BLOCK.
In Short: If an exception is thrown, it must be captured or the program terminates Execution.
PHP Error Exception handling detailed "reprint"