Home > Backend Development > PHP Tutorial > PHP exception handling, error throwing and callback functions and other object-oriented error handling methods_PHP tutorial

PHP exception handling, error throwing and callback functions and other object-oriented error handling methods_PHP tutorial

WBOY
Release: 2016-07-21 15:14:40
Original
869 people have browsed it

Exception handling is used to alter the normal flow of a script when a specified error (exception) condition occurs. This situation is called an exception.
PHP 5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Every try must have at least one corresponding catch. Use multiple catches to catch exceptions generated by different classes. When the try block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code continues execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.

When an exception is thrown, the subsequent code (Translator's Note: refers to the code block when the exception is thrown) will not continue to execute, and PHP will try to find the first one that can match The matching catch. If an exception is not caught and is not handled accordingly using set_exception_handler(), PHP will generate a serious error and output an Uncaught Exception... (uncaught exception) message.

When an exception is triggered, what typically happens:
• The current code state is saved
• Code execution is switched to a predefined exception handler function
•Depending on the situation, the processor may restart code execution from the saved code state, terminate script execution, or continue script execution from another location in the code

1. Error and exception level constant table
error: A runtime error that cannot be found during compilation. It is better to try to use echo to output an unassigned variable. Such problems often cause the program or logic to be unable to continue and need to be interrupted;
exception: program execution Unexpected situations occur during the process, which are often feasible logically, but do not meet the application scenarios. For example, receiving a user name with a length that is in the wrong predetermined format. Therefore, exceptions mainly rely on coders to make pre-judgements and then throw them. After catching the exception, change the program flow to handle these situations without interrupting the program.
PHP’s definition of exceptions and errors does not seem to be very obvious, especially in lower versions of PHP.
Error and logging values ​​Constant Description Remarks
1 E_ERROR (integer)
Fatal runtime error. This type of error is generally an unrecoverable situation, such as a problem caused by memory allocation. The consequence is that the script terminates and does not continue to run.
2 E_WARNING (integer)
Runtime warning (non-fatal error). Only a prompt message is given, but the script does not terminate.
4 E_PARSE (integer)
Compile time syntax parsing error. Parsing errors are generated only by the parser.
8 E_NOTICE (integer)
Runtime notification. Indicates that the script encounters a situation that may appear as an error, but there may also be similar notifications in scripts that can run normally.
16 E_CORE_ERROR(integer)
A fatal error occurred 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 (non-fatal error) that occurred during PHP initialization startup. Similar to E_WARNING, but generated by the PHP engine core. since PHP 4
64 E_COMPILE_ERROR(integer)
Fatal compile-time error. Similar to E_ERROR, but generated by the Zend script engine. since PHP 4
128 E_COMPILE_WARNING(integer)
Compile time warning (non-fatal error). Similar to E_WARNING, but generated by the Zend scripting engine. since PHP 4
256 E_USER_ERROR(integer)
User-generated error message. Similar to E_ERROR, but is generated by the user using the PHP function trigger_error() in the code. since PHP 4
512 E_USER_WARNING(integer)
Warning message generated by the user. Similar to E_WARNING, but is generated by the user using the PHP function trigger_error() in the 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 the PHP function trigger_error() in the code. since PHP 4
2048 E_STRICT (integer)
Enable PHP's suggestions for code modifications to ensure the best interoperability and forward compatibility of the code. since PHP 5
4096 E_RECOVERABLE_ERROR(integer)
A fatal error that can be caught. It indicates that a potentially dangerous error has occurred, but has not caused the PHP engine to become unstable. If the error is not caught by a user-defined handler (see set_error_handler()), it will become an E_ERROR and the script will terminate. since PHP 5.2.0
8192 E_DEPRECATED(integer)
Runtime notification. When enabled, a warning will be given about code that may not work properly in future versions. since PHP 5.3.0
16384 E_USER_DEPRECATED(integer)
User generated warning message. Similar to E_DEPRECATED, but is generated by the user 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.30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

2. error_reporting() and try-catch, thrown
error_reporting() function can be obtained (not When passing parameters), set which exceptions the script handles (not all exceptions need to be handled, for example, E_CORE_WARNING, E_NOTICE, and E_DEPRECATED can be ignored). This setting will override the exception handling settings defined by the error_reporting option in php.ini.
For example:
error_reporting(E_ALL&~E_NOTICE); // Except for E_NOTICE, other exceptions will be triggered (the binary operation result of E_ALL&~E_NOTICE is: the value of the corresponding bit of E_NOTICE is set to 0) try-catch cannot be used in the class The automatic loading function __autoload() takes effect.
try-catch cannot be used to catch exceptions and errors, such as errors triggered by trigger_error(). Exceptions and errors are different.

Copy code The code is as follows:

try{
// you codes that 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( $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' );
}
[/code]
The structure of the Exception class: most of the methods are prohibited from being overridden (final)
Copy code 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 ) //Message thrown by exception
final public Exception getPrevious ( void ) //Previous exception
final public int getCode ( void ) / /Exception code, this is user-defined
final public string getFile (void) //The file path where the exception occurred
final public int getLine (void) //The line where the exception occurred
final public array getTrace (void) //Exception tracing information (array)
final public string getTraceAsString (void) //Exception tracing information (string)
public string __toString (void) //Trying to treat the exception object directly as a string Return value of calling sub-function when using
final private void __clone (void) //Call when cloning exception object
}

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 throw statement, the clause will be executed and no other catch clauses will be executed. clause, otherwise continue to try the next catch clause. Since Exception is the base class of all exception classes, the exceptions thrown will match it. If you use different processing methods according to different exception types, you should use the Exception type The catch clause goes last.
Exception is the base class of all exceptions. You can extend the exception class according to actual needs.
Copy code 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){ // This error object needs Declaration type
echo $err->errType();
}catch(ErrorException $err){ //ErrorException is an exception class added in PHP 5, inherited from Exception
echo 'error !';
}catch(Exception $err){
redirect('/error.php');
}

You may determine the type of exception in the catch clause, or Determine whether to handle the exception based on code and other information. If the code you unload the catch clause cannot properly handle the caught exception, you can continue to throw exceptions within the catch clause.

3. Exception exception callback function
Copy code The code is as follows:

set_exception_handler(callback functionName) //This function will be called when an exception of Exception or its subclass occurs
function exceptionHandlerFun($errObj){ // The callback function of Exception exception has only one parameter, which is thrown exception object.
//.......
}

Exception exception callback function cannot eliminate the exception by returning true like set_error_handler's callback function, even if the callback function After the exception is handled, the subsequent code will not continue to be executed, so if you want to continue executing the subsequent code, you must use try-catch.
But there is an exception: the script end callback function can be executed, and the callback function can be executed even if the thrown exception is not handled.
register_shutdown_function(callback functionName[,argument1,argument2,...]);
For example:
Copy code The code is as follows:

function shutdownfunction(){
echo 'script is end';
}

register_shutdown_function("shutdownfunction");
Because shutdownfunction() is in the script is executed at the end, so this callback function can call a function anywhere in the script, even if the function is defined after the error is thrown (the function definition is completed during the script compilation).

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 thereof value.
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 callback function can be triggered only when the error type thrown by trigger_error matches the definition range of user_error_type.
The setting of this value is similar to the error_reporting() function.
The first parameter (callbeck functionName):
A function name, the function can have 5 parameters, the first 2 of which are required, in order:
user_error_type thrown by trigger_error, trigger_error thrown errorMsg, the absolute path of the file where the error was thrown, the line number where the error was thrown, and the context when the error was thrown (an array containing all variables, functions, classes and other data in the scope where trigger_error() is located)
Return value of the callback function: If false is returned, the system error handling mechanism will continue to throw the error. Returning true or no return value will eliminate the error.
Errors triggered by trigger_error() will not be caught by try-catch exception catching statements.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326237.htmlTechArticleException handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception. PHP 5 adds an exception handling module similar to other languages. In...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template