Exception handling is used to change the normal process of a script when a specified error (exception) condition occurs. This condition is called an exception.
PHP 5 adds exception handling modules similar to those in other languages. Exceptions generated in PHP code can be thrown by a throw statement and captured by a catch statement. The code that requires exception handling must be placed inside a try code block to catch possible exceptions. Each try must have at least one catch corresponding to it. You can use multiple catches to catch exceptions that are generated by different classes. When the try code block no longer throws an exception or cannot find a catch that matches the thrown exception, the PHP code resumes execution after jumping 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 behind it (the code block where the exception was thrown) will not continue, and PHP will attempt to find the first catch to match it. If an exception is not captured and does not use Set_exception_handler () for the appropriate processing, then PHP will produce a serious error and output uncaught exception ... (The exception is not caught) prompt information.
typically occurs when an exception is triggered.:
• Current code state is saved
• Code execution is switched to pre-defined exception handler functions
• Depending on the situation, the processor may restart execution of the code from the saved code State, terminate the script execution, or resume execution of the script from another location in the code
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: In the process of implementation of unexpected situations, logic is often good, but not in line with the application scenario, such as receiving a long-length error in the predetermined format of the user name, 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 value constants Description remarks
1 e_error (integer)
Fatal run-time error. Such errors are generally unrecoverable situations, 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 the run.
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 encountered a situation that might behave as an error, but there may be similar notifications in a script that can run correctly.
E_core_error (integer)
A fatal error occurred during PHP initialization startup. This error is similar to E_error, but is generated by the core of the PHP engine. Since PHP 4
E_core_warning (integer)
PHP initialization warnings (non-fatal errors) that occur 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
E_user_error (integer)
User-generated error message. Similar to E_error, but is generated by the user himself using the PHP function Trigger_error () in the code. Since PHP 4
E_user_warning (integer)
User-generated warning message. Similar to e_warning, but is generated by the user himself using the PHP function Trigger_error () in the code. Since PHP 4
1024x768 E_user_notice (integer)
User-generated notification information. Similar to E_notice, but is generated by the user himself using the PHP function Trigger_error () in the code. Since PHP 4
2048 e_strict (integer)
Enable PHP recommendations for code modifications to ensure the best interoperability and forward compatibility of your code. Since PHP 5
4096 E_recoverable_error (integer)
A fatal error that can be captured. 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)
Run-time notifications. When enabled, warns you about code that might not work correctly in a future release. Since PHP 5.3.0
16384 e_user_deprecated (integer)
The user produces less warning messages. Similar to e_deprecated, but is generated by the user himself using the PHP function Trigger_error () in the code. Since PHP 5.3.0
30719 e_all (integer)
E_strict all error and warning messages that go out. 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&~e_notice); In addition to e_notice other exceptions are triggered (the result of the E_all&~e_notice binary operation is that the value of the e_notice corresponding bit is set to 0) Try-catch cannot take effect within the class's auto-load function __autoload ().
Try-catch cannot be used to catch exceptions, cannot catch errors, such as trigger_error () triggered errors, exceptions and errors are not the same.
Copy CodeThe code is as follows:
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) {
$template->render (' Error_preg ');
}
[/code]
Structure of the Exception class: Most of these methods are forbidden (final)
Copy CodeThe code is as follows:
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 where 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)//The return value of the child function is called when attempting to use the exception object as a string directly
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 are using different processing methods depending on the exception type, 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.
Copy CodeThe code is as follows:
CALSS MyException extends exception{
Public Errtype = ' default ';
Public function __construct ($errType = ") {
$this->errtype = $errType;
}
}
Thrown new MyException (); Throws an exception
try{
You codes this maybe cause an error
}catch (myexception $err) {//This Error object needs to declare type
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 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 the code that unloads the catch clause does not properly handle the caught exception.
third, the callback function of Exception exception
Copy CodeThe code is as follows:
Set_exception_handler (callback functionname)//The exception that occurs with exception or its subclasses is called by this function
function Exceptionhandlerfun ($ERROBJ) {///Exception 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 executed, so you must use Try-catch to proceed with the subsequent code.
However, 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:
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, 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.
Set_error_handler (Callbeck Functionname[,user_error_type]); Set a callback function for Trigger_error () to handle errors, including system-thrown errors 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 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.
Trigger_error () Triggered errors are not captured by the Try-catch exception capture statement.
http://www.bkjia.com/PHPjc/326237.html www.bkjia.com true http://www.bkjia.com/PHPjc/326237.html techarticle exception handling is used to change the normal process of a script when a specified error (exception) condition occurs. This condition is called an exception. PHP 5 adds exception handling modules similar to those in other languages. In the ...