Exception Handling is simple, but under what circumstances should we use Exception Handling? Today, I will introduce you to the usage of php exception handling, the specific operation details are as follows. Exception Handling is simple, but under what circumstances should we use Exception Handling? Today, I will introduce you to the usage of php exception handling, the specific operation details are as follows.
Script ec (2); script
First, let's take a look at the official explanation (Exception Handling). The last sentence above describes how to solve the association between exceptions and PHP errors.
What are the advantages and disadvantages of the exception and PHP error mechanisms? How should I use it?
According to the official instructions of PHP, the PHP error mechanism (Error Code) is used to input PHP error information before an exception occurs. The concept of exception can be viewed as a custom error mechanism in terms of adequacy, used to make up for the shortcomings of the PHP error mechanism (error code.
This shows that the information is convenient,Exception, which can contain more error information, such as error information, error code, number of wrong lines, files, and even error context, to avoid the problem that the error information is not rich..
This is performance. For performance issues of exception handling, the following figure shows the performance issues:
Note: One of the points in the figure is not rigorous, that is, when determining whether the last catch block is used, it will be judged at the same time (is_a). If so, it will be executed in the last catch block.
Performance and convenience are often a contradiction. You can choose your preferred one based on the scenario.
The last question to be discussed is the issue of obsessive-compulsive disorder. If all errors are abnormal, you will see try {} catch {} on the full screen. There are many errors and you have to decide how to solve them. This is the need to scale Custom exceptions in many frameworks (Too many possible Uncaught exceptions). It may be designed by the user.
Note: try {} catch {} cannot be used to deliver a WARNING error. You must define a function to capture the error. For example:
Set_error_handler (function (){
Throw new Exception ('ach! ');
});
Try {
$ Result = 4/0;
} Catch (Exception $ e ){
Echo "Divide by zero, I don't fear you! ". PHP_EOL;
$ Result = 0;
}
Restore_error_handler ();