PHP Exception Handling, error throw, and error callback Functions
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 conditions occur during program execution, which is logical but not applicable to application scenarios. For example, if a user name with a length exceeding the 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.
Error and log record valueConstantDescriptionRemarks
1 E_ERROR (integer) fatal runtime error. | Such errors are generally irrecoverable, such as memory allocation problems. 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. Syntax Parsing error during E_PARSE (integer) compilation. | Parsing errors are only generated by the analyzer.
8 E_NOTICE (integer) runtime notification. | Indicates that the script may experience errors, but similar notifications may occur in scripts that can run normally.
16 E_CORE_ERROR (integer) fatal error during PHP initialization startup. | This error is similar to E_ERROR, but is generated by the PHP engine core. Since PHP 4
32 E_CORE_WARNING (integer) Warning during PHP initialization startup (non-fatal error ). | It is similar to E_WARNING, but is generated by the core of the PHP engine. Since PHP 4
64 E_COMPILE_ERROR (integer) fatal compile-time error. | It is similar to E_ERROR, but is generated by the Zend script engine. Since PHP 4
128 E_COMPILE_WARNING (integer) Warning during compilation (non-fatal error ). | Similar to E_WARNING, but generated by the Zend script engine. Since PHP 4
256 error message generated by the E_USER_ERROR (integer) 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) warning information generated by the user. | 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. | 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) it is recommended to enable PHP to modify the code. | Ensures optimal code interoperability and forward compatibility, since PHP 5
4096 E_RECOVERABLE_ERROR (integer) fatal errors that can be captured. | 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. | If this feature is enabled, a warning will be given to codes that may not work properly in future versions. Since PHP 5.3.0
16384 E_USER_DEPRECATED (integer) warning information for a small number of households. | 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 in the field of E_STRICT.
* 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. iniError_reportingOptions.
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. It should be noted that the error and log record values are both a binary number and one bit is set to 1)
Try-catch cannot take effect in the automatic loading function _ autoload () of the class.
Try-catch is used to capture exceptions and cannot catch errors, such as errors triggered by trigger_error (). Exceptions and errors are different.
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 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' );}
Structure of the Exception class: Most of the methods are not allowed to be rewritten (final)
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 the Exception final public Exception getPrevious (void) // The previous Exception final public int getCode (void) // Exception Code, this is the custom final public string getFile (void) // the file path where an exception occurs. final public int getLine (void) // The row final public array getTrace (void) where an exception occurs) // exception tracking information (array) final public string getTraceAsString (void) // exception tracking information (string) public string _ toString (void) // The final private void _ clone (void) returned value of calling the sub-function when trying to directly use the exception object as a string}
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 need to 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 and can be expanded as needed.
Calss MyException extends Exception {public errType = 'default'; public function _ construct ($ errType = '') {$ this-> errType = $ errType ;}} try {// you codes that maybe cause an error thrown new MyException ('an error');} catch (MyException $ err) {// This error object needs to declare the type echo $ err-> errType ();} catch (ErrorException $ err) {// ErrorException is an Exception class added to PHP 5 to encapsulate errors as exceptions, which can better handle error messages and inherit from Exception echo 'error! ';} Catch (Exception $ err) {redirect ('/error. php ');}
You may judge 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 write in the catch clause cannot properly handle the caught exception, you can continue to throw an exception in the catch clause.
Iii. Exception callback function
Set_exception_handler ('exceptionhandlerfun ') // if an Exception occurs or its subclass Exception occurs, the function exceptionHandlerFun ($ errObj) will be called. {// The Exception callback function has only one parameter, 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, to continue executing the subsequent code, you must use try-catch. Exceptions caught in try-catch will not trigger exception_handler.
But there is one exception: even if the thrown exception is not processed, the script end callback function can be executed.
Register_shutdown_function (callback functionName [, argument1, argument2,...]);
For example:
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.
Register the processing function of the error (including the Error thrown by the system and the Error thrown by the user) and eliminate the error:
Set_error_handler (callback 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.
You can use set_error_handler () to proxy the error thrown by the PHP program to ErrorException so that the error can be displayed like an exception:
function error_handler($errorType, $errorMsg, $errorFile, $errorLine ) { echo '<div>; throw new ErrorException($errorMsg, 0, $errorType, $errorFile, $errorLine);}set_error_handler('error_handler');count();
Errors triggered by using trigger_error () are not caught by the try-catch exception capture statement.