In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "PHP exception handling, error throwing and callback functions and other object-oriented error handling methods". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Exception handling is used to change the normal flow of the script when a specified error (exception) occurs. This condition is called an exception.
PHP 5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by throw statements and caught by catch statements. Code that requires exception handling must be placed in a block of try code in order to catch possible exceptions. Each try must have at least one corresponding catch. Using multiple catch, you can catch exceptions generated by different classes. When the try code block no longer throws an exception or the catch can't be found to match the thrown exception, the PHP code continues to execute after jumping to the last catch. Of course, PHP allows (throw) exceptions to be thrown again within the catch code block.
When an exception is thrown, subsequent code will not continue to execute, and PHP will try to find the first catch that matches it. If an exception is not caught and it is not necessary to use set_exception_handler () to handle it, then PHP will generate a serious error and output a message that Uncaught Exception. (no exception was caught).
When an exception is triggered, it usually occurs:
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 execution of the script from another location in the code
1. Constant scale of errors and anomalies
Error: for run-time errors that cannot be found at compile time, it is better to try to output an unassigned variable with echo. Such problems often cause the program or logic to fail and need to be interrupted.
Exception: unexpected situations occur during the execution of the program, which are often logically feasible, but do not conform to the application scenario, such as receiving a user name with an incorrect length and a predetermined format. Therefore, the exception mainly depends on the encoder to make a pre-judgment and throw it. After catching the exception, the program flow is changed to deal with these situations without interrupting the program.
PHP's definition of exceptions and errors doesn't seem obvious, especially in earlier versions of PHP.
Error and logging value constant description remarks
1 E_ERROR (integer)
Fatal runtime error. Such errors are generally unrecoverable, such as problems caused by memory allocation. The consequence is that the script terminates and no longer runs.
2 E_WARNING (integer)
Runtime warning (non-fatal error). Only the prompt is given, but the script does not stop running.
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 be a similar notification in a script that works properly.
16 E_CORE_ERROR (integer)
A fatal error that 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
32 E_CORE_WARNING (integer)
PHP initializes warnings (non-fatal errors) that occur during startup. Similar to E_WARNING, but generated by the core of the PHP engine. Since PHP 4
64 E_COMPILE_ERROR (integer)
Fatal compile-time error. Similar to E_ERROR, but generated by the Zend scripting 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)
Error message generated by the user. Similar to E_ERROR, but generated by the user himself using the PHP function trigger_error () in the code. Since PHP 4
512 E_USER_WARNING (integer)
A warning message generated by the user. Similar to E_WARNING, but generated by the user himself 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 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 changes to the code to ensure optimal interoperability and forward compatibility. 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 yet caused the PHP engine to be in an unstable state. If the error is not caught by the user-defined handle (see set_error_handler ()), it becomes an E_ERROR and the script terminates. Since PHP 5.2.0
8192 E_DEPRECATED (integer)
Runtime notification. When enabled, warnings will be given to code that may not work properly in future releases. Since PHP 5.3.0
16384 E_USER_DEPRECATED (integer)
Warning message of low production by users. Similar to E_DEPRECATED, but generated by the user himself using the PHP function trigger_error () in the code. Since PHP 5.3.0
30719 E_ALL (integer)
All errors and warnings for E_STRICT outbound. 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously
2. Error_reporting () and try-catch, thrown
The error_reporting () function can get (when no parameters are passed) and set which exceptions the script handles (not all exceptions need to be handled, such as E_CORE_WARNING, E_NOTICE, 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); / / all exceptions are triggered except E_NOTICE (the result of E_ALL&~E_NOTICE 's binary operation is that the value of the corresponding bit of E_NOTICE is set to 0) try-catch cannot take effect in the class's autoload function _ _ autoload ().
Try-catch cannot be used to catch exceptions, errors cannot be caught, such as errors triggered by trigger_error (), exceptions and errors are different.
The copy 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 default exception handling class of the system.
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]
Structure of the Exception class: most of these methods are not overwritten (final)
The copy 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) / / Information thrown by exception
Final public Exception getPrevious (void) / / previous exception
Final public int getCode (void) / / exception code, which is user-defined
Final public string getFile (void) / / abnormal file Lujin
Final public int getLine (void) / / the line 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) / / call the return value of the subfunction when attempting to directly use the exception object as a string
Called when final private void _ _ clone (void) / / when an exception object is cloned
}
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, the clause will be executed instead of the other catch clause, otherwise you will continue to try the next catch clause. Because Exception is the base class of all exception classes, the exceptions thrown will match him. If you use different handling methods according to different types of exceptions, you should put the catch clause of type Exception at the end.
Exception is the base class for all exceptions. Exception classes can be extended according to actual needs.
The copy 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 that maybe cause an error
} catch (MyException $err) {/ / this error object needs to declare a type
Echo $err- > errType ()
} catch (ErrorException $err) {/ / ErrorException is an exception class added by PHP 5 and inherits from Exception
Echo 'error!'
} catch (Exception $err) {
Redirect ('/ error.php')
}
You may judge the type of exception in the catch clause, or decide whether to handle the exception based on information such as code. If the code that unloads the catch clause cannot properly handle the caught exception, you can continue to throw the exception in the catch clause.
3. Callback function of Exception exception
The copy code is as follows:
Set_exception_handler (callback functionName) / / this function is called when an exception occurs in Exception or its subclass
The callback function of the function exceptionHandlerFun ($errObj) {/ / Exception exception takes only one argument, the exception object that is thrown.
/ /.
}
The callback function of Exception exception cannot eliminate the exception by returning true like the callback function of set_error_handler. Even if the callback function handles the exception, the subsequent code will not be executed, so you must use try-catch if you want to continue to execute the subsequent code.
But there is one exception: the callback function at the end of the script can be executed, and the callback function can be executed even if the exception thrown is not handled.
Register_shutdown_function (callback functionName [, argument1,argument2,...])
For example:
The copy code is as follows:
Function shutdownfunction () {
Echo 'script is end'
}
Register_shutdown_function ("shutdownfunction")
Because shutdownfunction () is executed at the end of the script, a function anywhere in the script can be called within this callback function, even if the function definition is after the error is thrown (the function definition is completed at script compilation time).
4. Trigger_error (string errorMsg [, int user_error_type])
This function is used to actively trigger an error: user_error_type can only be a value of E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, or a combination of them.
Set_error_handler (callbeck functionName [, user_error_type]); / / sets a callback function for trigger_error () to handle errors, including errors thrown by the system 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 meets the defined range of user_error_type before the callback function can be triggered.
This value is set similar to the error_reporting () function.
The first parameter (callbeck functionName):
A function name that can have five parameters, the first two of which are required, in turn:
The user_error_type thrown by trigger_error, the errorMsg thrown by trigger_error, the absolute road strength of the wrong file, the line number of the error thrown, the context in which the error was thrown (an array containing all variables, functions, classes, and other data in the scope of trigger_error ())
The return value of the callback function: if false is returned, the system error handling mechanism continues to throw the error. If it returns true or no return value, the error is eliminated.
Errors triggered by trigger_error () are not caught by the try-catch exception catch statement.
"PHP exception handling, error throwing and callback functions and other object-oriented error handling" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.