Detailed discussion on misunderstanding and experience summary of Java exception handling (sharing)
This paper focuses on some misunderstandings in the selection and use of Java exceptions. I hope readers can skillfully master some precautions and principles of exception handling, and pay attention to summary and induction. Only when exceptions are handled well can we improve the basic literacy of developers, improve the robustness of the system, improve the user experience and improve the value of products.
Misunderstanding I. abnormal selection
Figure 1 Anomaly classification
Figure 1 describes the structure of exceptions. In fact, we all know that exceptions can be divided into detected exceptions and non detected exceptions, but the application of these two exceptions is confused in practice. Because it is convenient to use non detected exceptions, many developers think that detecting exceptions is useless. In fact, abnormal application scenarios can be summarized as follows:
1、 The calling code cannot continue and needs to be terminated immediately. There are too many possibilities of this situation, such as the server is not connected, the parameters are incorrect, and so on. These times are applicable to non detection exceptions, do not need to call the explicit capture and processing of the code, and the code is concise and clear.
2、 The calling code needs further processing and recovery. If sqlexception is defined as non detection exception, developers naturally think that sqlexception does not require explicit capture and processing of calling code when operating data, which will lead to serious situations such as connection not closing, transaction not rolling back, dirty data in dB, etc. precisely because sqlexception is defined as detection exception, Will drive developers to explicitly catch and clean up resources after code exceptions. Of course, after cleaning up resources, you can continue to throw non detection exceptions to prevent program execution. According to observation and understanding, most of the detected exceptions can be applied to tool classes. Java learning group 669823128
Myth 2: display exceptions directly on the page or client.
It is common to print exceptions directly on the client. Take JSP as an example. Once an exception occurs during code operation, the container will print the exception stack information directly on the page by default. In fact, from the perspective of customers, any exception has no practical significance. The vast majority of customers do not understand the exception information at all. Software development should also try to avoid presenting the exception directly to users.
Listing 1
As shown in the example code, the error code is introduced into the exception. Once an exception occurs, we just present the error code of the exception to the user, or convert the error code into a more understandable prompt. In fact, the error code here also contains another function, and developers can accurately know what type of exception has occurred according to the error code.
Misunderstanding III. pollution of code hierarchy
We often divide the code into different hierarchies such as service, business logic and Dao. The Dao layer contains methods to throw exceptions, as shown in Listing 2:
Listing 2
At first glance, there is no problem with the above code, but consider carefully from the perspective of design coupling. The sqlexception here pollutes the upper calling code. The calling layer needs to explicitly use try catch to catch or throw it further to a higher level. According to the design isolation principle, we can appropriately modify it to:
Listing 3
Misunderstanding IV. ignore exceptions
The following exception handling only outputs the exception to the console, which has no meaning. Moreover, there are exceptions here, which do not interrupt the program, and then call the code to continue to execute, resulting in more exceptions.
Listing 4
Can be reconstituted:
Listing 5
This misunderstanding is quite basic. Generally, we will not make this low-level mistake .
Myth 5: include exceptions in circular statement blocks
As shown in the following code, the exception is contained in the for loop statement block.
Listing 6
We all know that exception handling takes up system resources. At first glance, everyone thought they would not make such a mistake. From another point of view, a loop is executed in class A. The method of B class is invoked in the loop. The method called in the B class contains the block of statement such as try-catch. Remove the hierarchy of classes, and the code is the same as above.
Myth 6: use exception to catch all potential exceptions
Several different types of exceptions are thrown during the execution of a method. In order to simplify the code, use the base class exception to catch all potential exceptions, as shown in the following example:
Listing 7
Can be reconstituted
Listing 8
Myth 7. Multi level encapsulation throws non detection exceptions
If we insist that different types of exceptions must use different capture statements, most examples can bypass this section. However, if only one piece of code call will throw more than one exception, it is often unnecessary to write a catch statement for each different type of exception. For development, any exception is enough to explain the specific problems of the program.
Listing 9
If we convert all exceptions into runtimeException as shown in the above example, when the type of exception is already runtimeException, we encapsulate it again. The runtimeException is encapsulated again, and the valid information carried by the original runtimeException is lost.
The solution is that we can add relevant checks in the runtimeException class to confirm that the parameter throwable is not an instance of runtimeException. If yes, copy the corresponding attributes to the new instance. Or use different catch statement blocks to catch runtimeexceptions and other exceptions. Personal preference mode 1, the benefits are self-evident.
Error 8. Multi level printing exception
Let's take a look at the following example, which defines two classes a and B. One class calls the B class code, and class A and B class capture the print exception.
Listing 10
The same exception will be printed twice. If the hierarchy is a little more complex, it is a headache to locate the specific problems in the exception log without considering the system performance consumed by printing the log.
In fact, the print log only needs to capture and print at the outermost layer of the code. Exception printing can also be written as AOP and woven into the outermost layer of the framework.
Myth 9: the information contained in the exception cannot fully locate the problem
Exceptions should not only let developers know what is wrong, but also more often developers need to know what causes the problem. We know Java Lang. exception has the construction method of string type parameters. This string can be customized into easy to understand prompt information.
For simple user-defined information, developers can only know where exceptions occur, but in many cases, developers need to know what parameters cause such exceptions. At this time, we need to add the parameter information of the method call to the user-defined information. The following example only lists the case of one parameter. In the case of multiple parameters, you can write a tool class to organize such a string.
Listing 11
Myth 10: failure to predict potential anomalies
In the process of writing code, due to the lack of deep understanding of the calling code, we can't accurately judge whether the calling code will produce exceptions, so we ignore the handling. After the production bug is generated, I remember that an exception catch should be added at a certain section of code, and I can't even accurately point out the cause of the exception. This requires developers not only to know what they are doing, but also to know what others have done and what results may result, and consider the processing process of the whole application from the overall situation. These ideas will affect our code writing and processing.
Misunderstanding 11. Mix a variety of third-party log Libraries
Nowadays, there are more and more types of Java third-party log libraries. A large project will introduce a variety of frameworks, and these frameworks will depend on the implementation of different log libraries. The most troublesome problem is not the introduction of all the required log libraries, but the incompatibility between the introduced log libraries. If it may be solved at the beginning of the project, you can reintroduce the log Library in all the code as needed, or change a framework. But not every project can afford such cost, and the more the project goes on, the greater the risk.
How can we effectively avoid similar problems? Most frameworks now have considered similar problems. You can configure properties or XML files, parameters, or scan the log implementation classes in the Lib library at runtime to really determine which specific log library to apply when the application is running.
In fact, according to the principle of not requiring multi-level log printing, we can simplify many classes that originally call log printing code. In many cases, we can use interceptors or filters to print logs and reduce the cost of code maintenance and migration.
Conclusion
The above is purely personal experience and summary. Everything is dialectical. There is no absolute principle. What suits you is the most effective principle. I hope the above explanation and analysis can be helpful to you.