Exception handling is used to change the normal flow of a script when a specified error (exception) condition occurs. This condition is called an exception.
PHP 5 Adds an exception-handling module similar to other languages. The exception generated in the PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed inside the try code block to catch possible exceptions. Each try must have at least one catch that corresponds to it. Use multiple catch to catch exceptions generated by different classes. When a try code block no longer throws an exception or cannot find a catch to match the thrown exception, the PHP code continues after the jump to the last catch. Of course, PHP allows you to throw (throw) exceptions again within a catch code block.
When an exception is thrown, the code that follows (the code block where the exception was thrown) will not continue, and PHP will try to find the first catch that matches it. If an exception is not captured, and does not use Set_exception_handler () for the corresponding processing, then PHP will produce a serious error, and output uncaught exception ... (Exception not caught) message.
When an exception is triggered, it usually occurs:
• Current code state is saved
• Code execution is switched to a predefined exception handler function
• Depending on the situation, the processor may restart execution of the code from the saved code State, terminate the script execution, or continue with the script from another location in the code
First, error, Exception level constants table
Error: It is not possible to discover Run-time errors at compile time, rather than trying to output an unassigned variable with the echo, which often leads to the inability of the program or logic to continue without interruption;
Exception: Unexpected situations occur during program execution, logically often, but not in line with the application scenario, such as receiving a long error in the predetermined format of the user name, therefore, the exception is mainly based on the coder to do a predetermined decision after the exception to catch exceptions to change the program process to deal with these situations, You do not have to interrupt the program.
The definition of exceptions and errors in PHP does not seem obvious, especially in the case of a lower version of PHP.
Error and Logging value Constants Description remarks
1 e_error (integer)
Fatal Run-time error. Such errors are generally unrecoverable, such as problems caused by memory allocation. The consequence is that the script terminates and no longer continues to run.
2 e_warning (integer)
Runtime Warning (non-fatal error). Only prompts are given, but the script does not terminate the operation.
4 E_parse (integer)
Compile-time syntax parsing error. Parsing errors are generated only by the parser.
8 E_notice (integer)
Run-time notifications. Indicates that the script encounters a situation that may behave incorrectly, but there may be similar notifications in a script that works well.
E_core_error (integer)
Fatal error that occurred during PHP initialization startup. The error is similar to E_error, but is generated by the PHP engine core. Since PHP 4
E_core_warning (integer)
A warning (non-fatal error) that occurred during the startup of PHP initialization. Similar to e_warning, but is generated by the PHP engine core. Since PHP 4
E_compile_error (integer)
Fatal compile-time error. Similar to E_error, but is generated by the Zend scripting engine. Since PHP 4
128 e_compile_warning (integer)
Compile-time warnings (non-fatal errors). Similar to e_warning, but is generated by the Zend scripting engine. Since PHP 4
256 E_user_error (integer)
The error message generated by the user. Similar to E_error, but is generated by the user using PHP functions trigger_error () in their code. Since PHP 4
E_user_warning (integer)
A warning message generated by the user. Similar to e_warning, but is generated by the user using PHP functions trigger_error () in their code. Since PHP 4
1024 E_user_notice (integer)
Notification information generated by the user. Similar to E_notice, but is generated by the user using PHP functions trigger_error () in their code. Since PHP 4
2048 e_strict (integer)
Enable PHP to modify your code to make sure that your code has the best interoperability and forward compatibility. Since PHP 5
4096 E_recoverable_error (integer)
Fatal error that can be caught. It indicates that a potentially very dangerous error has occurred, but has not caused the PHP engine to be in an unstable state. If the error is not captured by a user-defined handle (see Set_error_handler ()), it becomes a e_error and the script terminates. Since PHP 5.2.0
8192 e_deprecated (integer)
Run-time notifications. When enabled, you will be warned about code that might not work correctly in future versions. Since PHP 5.3.0
16384 e_user_deprecated (integer)
User-produced warning messages. Similar to e_deprecated, but is generated by the user using PHP functions trigger_error () in their code. Since PHP 5.3.0
30719 e_all (integer)
E_strict all errors and warnings out of the information. 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously
Second, error_reporting () and Try-catch, thrown
The error_reporting () function can get (without arguments), 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), which overrides Exception handling settings defined by the error_reporting option in php.ini.
For example:
Error_reporting (E_all&~e_notice); In addition to e_notice other exceptions will be triggered (e_all&~e_notice binary operation result is: E_notice corresponding bit value is set to 0) Try-catch cannot take effect in the class's Automatic load function __autoload ().
Try-catch cannot be used to catch exceptions, and cannot catch errors, such as Trigger_error ()-triggered errors, exceptions and errors.
try{
You codes which maybe cause an error
}catch (Exception $err) {//This Error object needs to declare the 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) {
$template->render (' Error_preg ');
}
[/code]
Structure of the Exception class: Most of these methods are forbidden to overwrite (final)
Exception {
/* Properties * *
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)//exception thrown information
Final public Exception getprevious (void)//Previous exception
Final public int getcode (void)//exception code, which is user-defined
Final public string getFile (void)//unexpected file path strength
Final public int getline (void)//The row in which the exception occurred
Final public array gettrace (void)//exception tracking information (array)
Final public string gettraceasstring (void)//Exception tracking information (string)
public string __tostring (void)//To call the return value of a child function when an exception object is used directly as a string
The final private void __clone (void)//is called when the exception object is cloned
}
extended Exception Class
Try-catch can have more than one catch clause, starting with the first catch clause, and if the exception variable type within the clause matches the exception type thrown by the thrown statement, the clause is executed and no more catch clauses are executed, otherwise the next catch clause continues, because the ex Ception is the base class for all exception classes, so the thrown exception matches him, and if you are using a different approach based on different exception types, you should put the Exception type's catch clause at the end.
Exception is the base class for all exceptions, and you can extend the exception class to the actual needs
CALSS MyException extends exception{
Public Errtype = ' default ';
Public function __construct ($errType = ' ") {
$this->errtype = $errType;
}
}
Thrown new MyException (); Throws an exception
try{
You codes which maybe cause an error
}catch (myexception $err) {//This Error object requires declaring type
echo $err->errtype ();
}catch (errorexception $err) {//errorexception is an added exception class for PHP 5, inherited from Exception
Echo ' Error! ';
}catch (Exception $err) {
Redirect ('/error.php ');
}
You may be able to determine the type of exception in the catch clause, or whether to handle the exception based on information such as code, and if you unload the catch clause to properly handle the caught exception, you can continue to throw the exception within the catch clause.
the callback function of the Exception exception
Set_exception_handler (callback functionname)//The exception of the exception or its subclasses will call this function
The callback function for a function exceptionhandlerfun ($ERROBJ) {//Exception exception has only one argument, which is the thrown exception object.
//.......
}
The Exception exception's callback function does not allow the exception to be eliminated by returning true, as the Set_error_handler callback function does, even if the callback function handles the exception and the subsequent code is not continued, so it is necessary to continue executing the subsequent code with Try-catch.
But there is one exception: the script-end callback function can be executed, and the thrown exception can be executed even if it is not processed.
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 callback function can call a function anywhere in the script, even if the function is defined after the error is thrown (the function definition was completed during the script compilation period).
Fourth. 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 its combination of values.
Set_error_handler (Callbeck Functionname[,user_error_type]); Set a callback function for Trigger_error () to handle errors, including errors thrown by the system and errors triggered by the user using the Trigger_error () function.
Optional parameter User_error_type:
If this parameter is set, the error type thrown by Trigger_error conforms to the defined scope 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 that can have 5 parameters, of which the first 2 must be selected, followed by:
Trigger_error thrown User_error_type, trigger_error thrown errormsg, absolute road strength of the file that threw the error, line number to throw the error, and context when the error was thrown (an array that contains the Trigger_ Error () All variables, functions, classes, and other data in the scope
Return value of the callback function: If False, the system error handling mechanism still continues to throw the error, returns TRUE or no return value to eliminate the error.
Trigger_error ()-triggered errors are not captured by Try-catch exception capture statements.