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

Source: Internet
Author: User
Tags php exception handling
PHP5 provides a new object-oriented error handling method, including PHP exception handling, error throws, and callback functions, for more information, refer to the normal process of exception handling to change 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.

The 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 ');
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 ');
Structure of the Exception class: most of the methods are not allowed to be rewritten (final)

The 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,

The code is as follows:

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

The 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:

The 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: 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.