Understanding of the exception mechanism in php

Source: Internet
Author: User
Tags php book php exception handling
The exception mechanism in php can only be regarded as an alternative. The exception mechanism is rarely discussed in the php book, and most of them only stay in the syntax stage. Some people praised the exception of php as a good thing, and some people think that the exception of php is very bad. some people have been confused about whether to use different exceptions in php...

The exception mechanism in php can only be regarded as an alternative. The exception mechanism is rarely discussed in the php book, and most of them only stay in the syntax stage. Some people praised the exception of php as a good thing. some people think that the exception of php is very bad. some people have been confused about how to use it in php?

The syntax of the exception itself is not worth discussing. The exception usage scenario is the main one. here I will compare php and java to see what the exceptions in php are and how they should be used.
I saw this discussion on the PPC Forum and thought it was very valuable. I reorganized my points and made a summary.
First, you need to say that the exception here refers to the php exception. Because php exceptions are significantly different from other languages.
An exception in php is a situation where the program running does not meet the expectation. that is, an exception is allowed in the program execution process, but different from the normal process. It is an abnormal situation, that is, errors that should not be made according to our normal logic, but still occur, are logical and business process errors, rather than syntax errors.
Errors in php are illegal. syntax or environment problems cause the compiler to fail the check or even run.
Php exception handling is to handle a certain situation that occurs when your program is running. it is not an error. An exception is the result that the program is running and not what you want. For programs, exceptions are uncontrollable. we cannot control the links in which errors will occur during the operation, but we can roughly predict the links where errors will occur and conduct targeted remediation.
Exception and error are different in different languages. Errors and exceptions are defined differently in java and php. In php, an error is triggered when it encounters any of its own errors, rather than throwing an exception (in some cases, exceptions and errors are thrown at the same time ). Once php encounters an abnormal code, it usually triggers an error instead of throwing an exception. In this sense, exceptions cannot be used to handle unexpected problems. For example, it is not feasible to trigger an exception when the database connection cannot be opened because the file does not exist. This is an error in php. php throws it as an error and cannot automatically catch it as an exception. Java is different. java regards many behaviors as exceptions and can be captured.
Let's take the most intuitive and simple example. Take the typical zero division problem as an example:

The code is as follows:
// Exception. php
$ A = null;
Try {
$ A = 5/0;
Echo $ a, PHP_EOL;
} Catch (exception $ e ){
$ E-> getMessage ();
$ A =-1;
}
Echo $;

Running result:

The following is the java code: ExceptionTry. java

The code is as follows:
// ExceptionTry. java
Public class ExcepetionTry {
Public static void tp () throws ArithmeticException {
Int;
A = 5/0;
System. out. println ("calculation result:" + );
}

Public static void main (String [] args ){
Int;
Try {
A = 5/0;
System. out. println ("calculation result:" + );
} Catch (ArithmeticException e ){
E. printStackTrace ();
} Finally {
A =-1;
System. out. println ("calculation result:" + );
}
Try {
Required etiontry. tp ();
} Catch (Exception e ){
System. out. println ("exception caught ");
}

}
}

Running result:

If we change the second statement in the tp method to the following:
A = 5/1;
The result is as follows:

As you can see from the above running results, for the "exception" code except 0, php considers this as an error and will directly trigger the error (waring is also an error, but the error level is different ), the exception process is not automatically thrown, so the value of $ a is not-1 as expected. that is to say, it does not enter the exception branch, nor does it handle the exception. Php can only capture exceptions after throw (in general, some exceptions can be automatically captured by php ).
Exception handling mechanisms are used in the following three scenarios:
(1) pessimistic prediction of the program
If a programmer is pessimistic about his code, it does not mean that the programmer's code quality is not high. He thinks that his code cannot handle all kinds of foreseeable situations one by one, so the programmer will handle exceptions. Assume that in a scenario where a programmer is pessimistic about the possibility of a deadlock in a high concurrency, the programmer will throw an exception and capture the deadlock, handle exceptions in detail.
(2) program needs and business concerns
If programmers want the business code to be not flooded with printing, debugging, and other processing, they usually use the exception mechanism, or define their own exceptions in the business, in this case, you need to customize an exception to supplement various services in the real world. For example, if you are late for work, I think this is an exception. we need to collect it and handle it at the end of the month to deduct your salary; if a programmer wants to handle code that may affect normal business with foresight, it needs exceptions. It is emphasized that exceptions are essential for business processing and cannot be ignored. Exception mechanisms hold that data consistency is very important. when data consistency may be damaged, an exception mechanism is required to remedy it in advance.
For example, if you need to upload a file, you must store the uploaded file in a directory and insert the file record in the database, these two steps are an integrated service that is closely related to each other. If the file fails to be saved, the file cannot be downloaded if the inserted record is successful. if the database fails to write the file after the file is saved successfully, the unrecorded file will become a dead file and will never be downloaded.
Assume that no prompt is displayed after the file is successfully saved, but an exception is automatically thrown when the file fails to be saved. The same is true for accessing the database. if the file is inserted successfully, no prompt is displayed. if the file fails, an exception is automatically thrown, we can include the two code segments that may throw exceptions in a try statement, and capture errors in catch, delete files not recorded in the database or delete records without files in the catch code segment to ensure business data consistency. Therefore, from the business perspective, exceptions focus on protecting business data consistency, and emphasize the handling of abnormal businesses.
If our code is just a symbolic try-catch, the last error is printed, over. It is better to avoid such exceptions without reflecting the idea of exceptions. Therefore, the reasonable code should be as follows:

The code is as follows:
Try {
// Code segment that may fail
If (file Upload failed) throw (Upload exception );
If (failed to insert database) throw (database operation exception);} catch (exception ){
Necessary remedial measures, such as deleting files and deleting database insert records, are very meticulous.
}
//....
?>

You can also:

The code is as follows:
Upload {
If (file Upload failed) throw (Upload exception );
If (database insertion failed) throw (database operation exception );
}
// Other code... try {
Upload;
Others;
} Catch (Upload exception ){
Necessary remedial measures, such as deleting files and deleting database insert records
} Catch (other exceptions ){
Record log
}
?>

The preceding two methods are used to capture exceptions. The former is to capture exceptions immediately when exceptions occur, and the latter is to scatter and throw exceptions in a centralized manner. Which one should it be?
If our business is very important, the sooner the exception is handled, the better, to ensure that the program can maintain the consistency of business processing in case of exceptions. For example, if one operation has multiple prerequisite steps and the last step suddenly becomes abnormal, all other prerequisite operations must be eliminated to ensure data consistency. In addition, in this core business, there is a lot of code to do the aftermath and remedy the data. this is a pessimistic exception.
If exceptions are not so important, and in a single entry and MVC-style application, the latter exception handling method is often used to ensure the consistency of code processes, this exception handling emphasizes the business process trend and is not very concerned about the aftermath. This is an optimistic exception.
(3) language-level Robustness Requirements
Php is missing at this point. Taking java as an example, java is a language for enterprise-level development, emphasizing robustness. Java supports multithreading. java believes that the interruption of multithreading is completely unpredictable and unavoidable. Therefore, java stipulates that, when multithreading is used, this situation must be taken into consideration. You can either throw it or capture it for processing. In short, you must face the InterruptedException exception and are not allowed to avoid it. That is to say, you should remedy important data services after an exception occurs. of course you can leave it alone, but I will tell you that this is what you should do. Such exceptions are mandatory. More exceptions are not mandatory and are determined by the programmer. Java's exception classification and constraints ensure the robustness and trustworthiness of java programs.
So what is the significance of exceptions?
An exception is a running error that cannot be controlled. If an error occurs, the normal logical operation is interrupted. the logic behind the exception code cannot continue to run. The advantage of try/catch is that the logical interrupt damage caused by exceptions can be minimized, and the integrity of the business logic is not affected after remedial measures are taken, if you throw an exception or throw a capture, or capture the exception without remedy, the data may be disordered. This is an important role of exception handling, that is, when we precisely control the runtime process, when the program is interrupted, we may use try to narrow down the impact scope of errors, capture exceptions in a timely manner and make appropriate remedial measures so that the logical process can still return to the normal track.
How to check php exceptions?
We have seen that the exception mechanism in php is very weak. In most cases, exceptions cannot be automatically thrown. if-else must be used for first judgment, and then an exception is thrown manually. This processing method seems to be an alternative. Manually throwing an exception does not mean much, because you manually throwing an exception means that you have fully anticipated the error in the code, even if it is not really "abnormal", it is expected. It is still in complicated business logic judgment and processing. Java and C ++ are better at defining a bunch of built-in common exceptions, which are thrown manually after the programmer judges various exceptions, the compiler checks whether an error occurs in the service on our behalf and automatically throws an exception. As a programmer, you only need to focus on exception capture and subsequent remediation, rather than focusing on what exceptions will happen in php. use if-else to judge one by one and throw exceptions one by one.
The exception mechanism of php is not perfect. in many cases, it has no obvious advantage over if-else, which is also the reason why php exceptions are not popularized. Of course, exceptions can also reduce coupling to some extent.
So how can we improve the original php exception handling mechanism? At this time, it is necessary to use php to handle errors. PHP provides a set_error_handler function that allows you to customize error handling functions and redirect non-fatal error handling methods to your own defined functions for analysis and processing. However, there may be a lot of errors, and it is complicated to differentiate them in a centralized manner. Therefore, we only use this feature as a stepping stone. In the user-defined function, we manually throw an exception and kill a Trojan horse to allow try/catch to capture and handle the interruption caused by this running error, in this way, the impact scope of try/catch can be expanded.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.