PHP Exception Handling, error throws, callback functions, and other object-oriented error handling methods

Source: Internet
Author: User
Tags php exception handling

Exception Handling is used to change the normal process of the script when a specified error (exception) occurs. This is called an exception.
PHP 5 adds an exception handling module similar to other languages. 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.

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 location in the code

I. Error and exception level constant table
Error: a runtime error cannot be found during compilation. It is better to use echo to output an unassigned variable. Such problems often lead to program or logic interruptions;
Exception: unexpected situations occur during program execution, which may be logical but not applicable to application scenarios. For example, if a user name with a long length or wrong predefined format is received, an exception is thrown by the encoding staff after making a pre-judgment. After the exception is captured, the program process is changed to deal with these situations without interrupting the program.
PHP does not seem to clearly define exceptions and errors, especially for earlier versions of PHP.
Description of errors and log record value Constants
1 E_ERROR (integer)
Fatal runtime error. Such errors are usually irrecoverable, such as problems caused by memory allocation. The consequence is that the script stops running.
2 E_WARNING (integer)
Run-Time Warning (non-fatal error ). Only prompts are provided, but the script does not stop running.
4 E_PARSE (integer)
Syntax Parsing error during compilation. Parsing errors are only generated by the analyzer.
8 E_NOTICE (integer)
Runtime notification. Indicates that the script may be incorrectly displayed, but similar notifications may occur in scripts that can run normally.
16 E_CORE_ERROR (integer)
A fatal error occurs during PHP initialization and startup. This error is similar to E_ERROR, but is generated by the core of the PHP engine. Since PHP 4
32 E_CORE_WARNING (integer)
Warning during PHP initialization startup (non-fatal error ). It is similar to E_WARNING, but it is generated by the core of the PHP engine. Since PHP 4
64 E_COMPILE_ERROR (integer)
Fatal compilation error. It is similar to E_ERROR, but it is generated by the Zend script engine. Since PHP 4
128 E_COMPILE_WARNING (integer)
Compile-time warning (non-fatal error ). It is similar to E_WARNING, but it is generated by the Zend script engine. Since PHP 4
256 E_USER_ERROR (integer)
Error message generated by the user. It is similar to E_ERROR, but it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
512 E_USER_WARNING (integer)
User-generated warning information. It is similar to E_WARNING, but it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
1024 E_USER_NOTICE (integer)
User-generated notification information. It is similar to E_NOTICE, but it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
2048 E_STRICT (integer)
Enable PHP code modification suggestions to ensure the best code interoperability and forward compatibility. Since PHP 5
4096 E_RECOVERABLE_ERROR (integer)
Possible fatal errors. It indicates that a potentially dangerous error has occurred, but it has not caused the PHP engine to be unstable. If the error is not captured by the custom handle (see set_error_handler (), it becomes an E_ERROR and the script stops running. Since PHP 5.2.0
8192 E_DEPRECATED (integer)
Runtime notification. When enabled, a warning will be given to code that may not work properly in future versions. Since PHP 5.3.0
16384 E_USER_DEPRECATED (integer)
User-generated warning information. It is similar to E_DEPRECATED, but it is generated by the user using the PHP function trigger_error () in the code. Since PHP 5.3.0
30719 E_ALL (integer)
All error and warning information of the E_STRICT field. 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previusly

Ii. error_reporting () and try-catch and thrown
The error_reporting () function can obtain (when no parameter is passed) and set the exceptions to be handled by the script (not all exceptions need to be handled, for example, E_CORE_WARNING, E_NOTICE, and E_DEPRECATED can be ignored ), this setting will overwrite php. the error handling settings defined by the error_reporting option in ini.
For example:
Error_reporting (E_ALL &~ E_NOTICE); // other exceptions except E_NOTICE will be triggered (E_ALL &~ The binary operation result of E_NOTICE is: the value of the corresponding bits of E_NOTICE is set to 0. try-catch cannot take effect in the automatic loading function _ autoload () of the class.
Try-catch cannot be used to capture exceptions and cannot catch errors, such as errors triggered by trigger_error (). Exceptions and errors are different.Copy codeThe Code is as follows: try {
// You codes that maybe cause an error
} Catch (Exception $ err) {// The type of this error object needs to be declared. Exception is the default Exception handling class of the system.
Echo $ err-> getMessage ();
}

// Thrown can throw an exception, for example:
Thrown new Exception ('an error ');
Example:
Try {
If (empty ($ var1) throw new NotEmptyException ();
If (empty ($ var2) throw new NotEmptyException ();
If (! Preg_match () throw new InvalidInputException ();
$ Model-> write ();
$ Template-> render ('success ');
} Catch (NotEmptyException $ e ){
$ Template-> render ('error _ empty ');
} Catch (InvalidInputException $ e ){
$ Template-> render ('error _ preg ');
}
[/Code]
Structure of the Exception class: Most of the methods are not allowed to be rewritten (final)Copy codeThe Code is as follows: Exception {
/* Attribute */
Protected string $ message;
Protected int $ code;
Protected string $ file;
Protected int $ line;
/* Method */
Public _ construct ([string $ message = "" [, int $ code = 0 [, Exception $ previous = null])
Final public string getMessage (void) // information thrown by an exception
Final public Exception getPrevious (void) // previous Exception
Final public int getCode (void) // Exception Code, which is user-defined
Final public string getFile (void) // file path strength in case of an exception
Final public int getLine (void) // the row with an exception
Final public array getTrace (void) // exception tracking information (array)
Final public string getTraceAsString (void) // exception tracking information (string)
Public string _ toString (void) // the return value of the subfunction called when an exception object is used as a string.
Final private void _ clone (void) // called when an exception object is cloned
}

Extended exception class
Try-catch can have multiple catch clauses. Starting from the first catch clause, if the exception variable type in the clause matches the exception type thrown by the thrown statement, this clause is executed instead of other catch clauses. Otherwise, the next catch clause will be attempted. Because Exception is the base class of all Exception classes, the thrown Exception will match it, if you use different processing methods based on different Exception types, put the catch clause of the Exception type at the end.
Exception is the base class of all exceptions. You can extend the Exception class as needed,Copy codeCode: calss MyException extends Exception {
Public errType = 'default ';
Public function _ construct ($ errType = ''){
$ This-> errType = $ errType;
}
}
Thrown new MyException (); // throw an exception
Try {
// You codes that maybe cause an error
} Catch (MyException $ err) {// The type of this error object needs to be declared
Echo $ err-> errType ();
} Catch (ErrorException $ err) {// ErrorException is an Exception class added to PHP 5, inherited from Exception
Echo 'error! ';
} Catch (Exception $ err ){
Redirect ('/error. php ');
}

You may determine the exception type in the catch clause, or decide whether to handle the exception based on the code or other information. If the code you uninstall the catch clause cannot properly handle the caught exception, you can continue to throw an exception in the catch clause.

Iii. Exception callback function Copy codeThe Code is as follows: set_exception_handler (callback functionName) // if an Exception occurs or its subclass Exception occurs, this function is called.
Function exceptionHandlerFun ($ errObj) {// The callback function with Exception has only one parameter, that is, the thrown Exception object.
//.......
}

The Exception callback function does not return true as the set_error_handler callback function does. Even if the callback function handles exceptions, subsequent code will not be executed, therefore, try-catch is required to continue executing the subsequent code.
But there is one exception: the callback function can be executed after the script ends. Even if the thrown exception is not processed, the callback function can also be executed.
Register_shutdown_function (callback functionName [, argument1, argument2,...]);
For example:Copy codeThe Code is as follows: function shutdownfunction (){
Echo 'script is end ';
}

Register_shutdown_function ("shutdownfunction ");
Because shutdownfunction () is executed at the end of the script, the function at any position in the script can be called in this callback function, even if the function is defined after the error throw position (the function definition is completed during the script compilation period ).

4. trigger_error (string errorMsg [, int user_error_type])
This function is used to actively trigger an error: user_error_type can only be E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, or a combination of values.
Set_error_handler (callbeck functionName [, user_error_type]); // set a callback function for trigger_error () to handle errors, including system errors and errors triggered by users using the trigger_error () function.
Optional parameter user_error_type:
If this parameter is set, the error type thrown by trigger_error must be within the defined range of user_error_type to trigger the callback function.
The setting of this value is similar to the error_reporting () function.
The first parameter (callbeck functionName ):
A function name. The function can have five parameters. The first two parameters are required:
User_error_type thrown by trigger_error, errorMsg thrown by trigger_error, absolute path strength of the file that throws the error, row number that throws the error, and context environment when the error is thrown (an array containing trigger_error () all variables, functions, classes, and other data in the scope)
Return Value of the callback function: if false is returned, the system error processing mechanism continues to throw this error. If true is returned or no return value is returned, the error is eliminated.
Errors triggered by trigger_error () are not caught by the try-catch exception capture statement.

Related Article

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.