PHP exception handling, error throwing, and error callback functions

Source: Internet
Author: User
Tags php exception handling terminates zend

Error, Exception level constants table

Error: The run-time error cannot be found at compile time, instead of trying to output an unassigned variable with echo, this kind of problem often causes the program or logic to not continue and needs to be interrupted;

Exception: Unexpected situations occur in the process of the program execution, the logic is often good, but does not conform to the application scenario, for example, received a length beyond the predetermined format of the user named, therefore, the exception is mainly by the coding staff to do pre-judgment thrown, after catching the exception to change the program flow to deal with these situations, You do not have to interrupt the program.

PHP's definition of exceptions and errors does not seem obvious, especially in the case of a lower version of PHP.

error and log record values                            Constants                                             Description Notes
1 e_error (integer) Fatal run-time error. | Such errors are generally unrecoverable, such as problems caused by memory allocations. The result is that the script terminates and no longer continues to run.

2 e_warning (integer) Run-time warning (non-fatal error). Only the prompt is given, but the script does not terminate.

4 E_parse (integer) Compile-time parsing error. Parsing errors are only generated by the parser.

8 E_notice (integer) runtime notification. | Indicates that the script encountered a situation that might appear to be an error, but there may be similar notifications in a script that can run correctly.

E_core_error (integer) PHP Initializes a fatal error that occurs during startup. This error is similar to E_error, but is generated by the PHP engine core. Since PHP 4

E_core_warning (integer) PHP Initializes a warning (non-fatal error) that occurs during startup. | Similar to E_warning, but generated by the core of the PHP engine. Since PHP 4

E_compile_error (integer) Fatal compile-time error. | Similar to E_error, but generated by the Zend scripting engine. Since PHP 4

E_compile_warning (integer) Compile-time warning (non-fatal error). | Similar to E_warning, but generated by the Zend scripting engine. Since PHP 4

The error message generated by the E_user_error (integer) user. | Similar to E_error, but is generated by the user using PHP functions trigger_error () in the code. Since PHP 4

The warning message generated by the e_user_warning (integer) user. | Similar to E_warning, but is generated by the user using PHP functions trigger_error () in the code. Since PHP 4

E_user_notice (integer) User-generated notification information. | Similar to E_notice, but is generated by the user using PHP functions trigger_error () in the code. Since PHP 4

2048 e_strict (integer) enables PHP to modify the code recommendations. | Ensure the best interoperability and forward compatibility of your code, since PHP 5

4096 E_recoverable_error (integer) can be captured by a fatal error. | It indicates that a potentially very dangerous error has occurred, but has not yet caused the PHP engine to be in an unstable state. If the error is not captured by the user custom handle (see Set_error_handler ()), it becomes a e_error and the script terminates. Since PHP 5.2.0

8192 e_deprecated (integer) runtime notification. | When enabled, a warning will be given to code that may not work correctly in a future release. Since PHP 5.3.0

16384 e_user_deprecated (integer) Low warning message. | Similar to e_deprecated, but generated by the user's own use of the PHP function Trigger_error () in the code. Since PHP 5.3.0

30719 e_all (integer) e_strict all error and warning messages out of the outbound.

*30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

II, Error_reporting () and Try-catch, thrown

The error_reporting () function can get (when no parameter is passed), set what exceptions the script handles (not all exceptions need to be handled, such as E_core_warning, E_notice, e_deprecated can be ignored), and the setting overrides Exception handling settings defined by the error_reporting option in php.ini.

For example:

Error_reporting (e_all&~// except E_notice Other exceptions will be triggered (the result of the binary operation of the e_all&~e_notice is that the value of the e_notice corresponding bit is set to 0, It should be noted that both the error and the logging value are a binary number and one is set to 1)  

Try-catch cannot take effect within the class's auto-load function __autoload ().

Try-catch is used to catch exceptions, cannot catch errors, such as trigger_error () triggered errors, exceptions and errors are not the same.

try{  //You codes this maybe cause an error}catch (Exception $err) {//This Error object needs to declare type, Exception is the system default exception handling class    echo $err ->getmessage ();} Thrown can throw an exception, such as: Thrown new Exception (' an error ');

An example:

try {    if (empty ($var 1)) throw new Notemptyexception ();    if (Empty ($var 2)) throw new Notemptyexception ();    if (! Preg_match ()) throw new Invalidinputexception ();    $model->write ();    $template->render (' success ');  } catch (Notemptyexception $e) {  $template->render (' Error_empty ');} catch (Invalidinputexception $e) {  $tem Plate->render (' Error_preg ');}

Structure of the Exception class: Most of these methods are forbidden (final)

Exception {/* Property */protected string $message;p rotected int $code;p rotected string $file;p rotected int $line;/* Method */pu  Blic __construct ([String $message = "" [, int $code = 0 [, Exception $previous = null]]) final public string getMessage (void)//exception-thrown information final public Exception getprevious (void)//Previous exception final public int getcode (void)//exception code, which is user-defined Fina  L public string getFile (void)//exception file path strength final public int getLine (void)//Exception line final public array gettrace (void) Exception tracking Information (array) final public string gettraceasstring (void)//Exception trace information (string) public string __tostring (void)//attempt to directly add an exception The return value of the child function is called when the object is used as a string final private void __clone (void)//Clone exception object when called}

Extended Exception class

Try-catch can have more than one catch clause, starting with the first catch clause, if the exception variable type in the clause matches the exception type thrown by the thrown statement, the clause is executed without executing the other catch clause, otherwise the next catch clause continues to be attempted because the ex Ception is the base class for all exception classes, so throwing exceptions matches him, and if you need to use different processing methods based on different exception types, you should put the catch clauses of the Exception type to the end.

Exception is the base class for all exceptions, and you can extend the exception class according to your actual needs

CALSS MyException extends exception{public   errtype = ' default ';   Public function __construct ($errType = ") {      $this->errtype = $errType;  }} try{  //You codes that maybe Cause an error   thrown the 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 the error as an exception, better handle the error message, inherit from the Exception   echo ' Error! ';} catch (Exception $err) {   Redirect ('/error.php ');}

You might be able to determine the type of the exception in the catch clause, or decide whether to handle the exception based on the information such as code, and you can continue to throw an exception within the catch clause if you write a catch clause that does not properly handle the caught exception.

Third, the callback function of Exception exception

Set_exception_handler (' Exceptionhandlerfun ')  //The exception that occurs exception or its subclasses is called when this function functions Exceptionhandlerfun ($ Errobj) {  ///Exception The exception's callback function has only one parameter, which is the exception object thrown. //.......}

The callback function of the Exception exception cannot be eliminated by returning true as the callback function of Set_error_handler, even if the callback function handles the exception and the successor code is not continued, so you must use Try-catch to proceed with the subsequent code. An exception that is caught in Try-catch does not trigger exception_handler.

However, there is one exception: if the thrown exception is not handled, 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, this callback function can invoke functions anywhere in the script, even after the function is defined in the wrong throw position (the function definition is done during the scripting compile time).

Iv. trigger_error (String errormsg[,int User_error_type])

This function is used to proactively trigger an error: User_error_type can only be e_all, E_user_error, e_user_warning, E_user_notice, or its combined value.

Register error (including system-thrown error and user-thrown error) handler functions and Eliminate error:

Set_error_handler (//  

Optional parameter User_error_type:

If this parameter is set, the error type thrown by Trigger_error conforms to the defined range of User_error_type to trigger the callback function.

The setting of this value is similar to the error_reporting () function.

First parameter (callbeck functionname):

A function name, the function can have 5 parameters, of which the first 2 must be selected, in turn:

Trigger_error throws the User_error_type, Trigger_error throws the errormsg, throws the wrong file's absolute path, throws the wrong line number, throws the error when the context (an array that contains the Trigger_ All variables, functions, classes, and so on in the scope of the error ()

Return value of the callback function: If False is returned, the system error handling mechanism continues to throw the error, returning TRUE or no return value to eliminate the error.

You can use Set_error_handler () to send an error proxy thrown by a PHP program to errorexception so that the error can appear like an exception:

function Error_Handler ($errorType, $ERRORMSG, $errorFile, $errorLine) {    echo ' <div style= "color:red;" >error_handler is called!</div> ';    throw new Errorexception ($ERRORMSG, 0, $errorType, $errorFile, $errorLine);} Set_error_handler (' Error_Handler '); count ();

Errors triggered by the user using Trigger_error () are not captured by the Try-catch exception capture statement.

PHP exception handling, error throwing, and error callback function (GO)

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.