Java exception handling: a layer of insurance for programs

In one's life, one will always encounter some unexpected troubles, which may give us a heavy blow. In order to reduce the burden, we will buy insurance.

With a responsible attitude, we programmers are very rigorous when writing code. However, when the program is running, there are often some unexpected errors, resulting in unexpected events. In the end, the program does not execute normally according to our expectations - when an exception occurs, do you let the program live and die, or output the error to the user?

The solution provided by Java is exception handling mechanism.

The exception handling mechanism enables the program to handle exceptions according to the preset exception handling rules of the code when exceptions occur - either restore to the beginning of the program, or stop running, throw out the detailed error information, let us programmers know what went wrong, and then make corresponding optimization.

Exception handling mechanism ensures the robustness of the program to a certain extent, just like covering the program with a layer of insurance.

In Java, exceptions are called throwable, It can be divided into error and exception. Error: represents the Java virtual machine (Java virtual machine) errors cannot be handled by code. The most familiar error for programmers is outofmemoryerror. The reason for this error is that the program is not rigorous and generates too much garbage, resulting in Java virtual machine memory overflow. Exception: represents various exceptions (unexpected events) during program operation, which can be divided into check (checked) exceptions and non checks (unchecked) exception. The compiler forces the programmer to do preprocessing work for checking exceptions - catch exceptions and handle or throw exceptions, otherwise the compiler will prompt errors. Common exceptions of this kind are sqlexception, IOException and classnotfoundexception. The compiler does not prompt non checked exceptions and does not require them to be handled in the program. But usually In this case, programmers should guard against these exceptions. For example, check the divisor when performing division operation to ensure that it cannot be 0, otherwise the program will throw arithmeticexception when running. If such an exception occurs, it can only show that the programmer who wrote this code is careless. You can see the following figure to understand the classification of Java exceptions:

Look at program listing 3-1: when the divisor is 0, an arithmeticexception exception will be thrown, and the program will not continue to execute - the exception information is printed in great detail. We can find out which line is wrong and know that the error is caused by the divisor of 0; If you don't know how to solve the error, you can copy and paste the error information in the first line for search. There are many answers you need.

Listing 3-1 does not use the exception handling mechanism and can be compiled smoothly because the arithmeticexception exception is a non check exception. What if you encounter a check exception? The compiler will remind that the exception is not handled, as shown in the figure below: insert a picture here to describe the specific code as follows: how to handle the exception? If it is a non check exception, you need to avoid possible errors in the coding stage. For example, check whether the divisor is 0. If it is 0, do not perform division operation again. There are two ways to check for exceptions. 1) When I was about to graduate from University, I felt very confused and didn't know what to do in the future, so I called my parents for help, and they advised me to go to a software training park for training - if I couldn't decide, I asked my superiors for instructions. This realistic scenario can even find similarities in Java. When a method does not know how to handle an exception, it can use the throws keyword to throw the error prompted by the compiler, and the thrown error is directly handed over to the method caller for processing. Examples are as follows: 2) after two months of training in the software training park, I was hired by Jiangsu Fujitsu, and then worked for three and a half years. Over the past three years, I have grown up a lot and my skills have been greatly trained, so I returned to Luoyang five years ago - this time, I didn't ask my parents for instructions, because my wings are hard and I can make my own decisions. This realistic scenario can still find similarities in Java. When a method knows how to handle exceptions, it can use the try block to capture the code segment reminded by the compiler of errors, and then make corresponding processing in the catch block. Examples are as follows: when I first learned Java, I always liked to catch general exceptions directly, Not specific exceptions (such as FileNotFoundException), because it is easy to do so. In addition to writing a few letters less, there is no need to worry about catching other exceptions when they occur. But this is problematic. Because in daily development, we hope that the code can intuitively reflect as much information as possible, but unspecified exceptions will hide the information that should be presented.

1) Form validation when we need to check the content entered by the user on the server side, we can use the exception handling mechanism. How? The first step is to customize the exception class, Inherit runtimeException (those unchecked exception classes inherit from this class). Step 2: when the form is verified, when the user input does not meet the requirements, use the throw keyword to throw a user-defined exception. Step 3: capture the user-defined exception and deal with it accordingly. Why use the user-defined exception to deal with the user input? Because the user input needs to check many items, which vary Often, the processing mechanism will stop when the first error is encountered, and the subsequent code will not be executed - which is very suitable for the scenario of form verification. 2) Log the stack information of exceptions. In previous examples, we always print the error information on the console, but in formal applications, the log should be recorded in the log file because the information recorded by the console is limited. Due to space limitations, please refer to resources for log related components log4j, slf4j and their configurations in the project. After configuring the log component, you can create a logger in the class that needs to record log information, and then use the logger in the catch block error(e.getMessage(),e); Record detailed exception stack information. Specific examples are as follows:

For some code, we hope that no matter whether the exception in the try block is thrown or not, they can be executed. This requires finally -- no matter whether the exception occurs or not, as long as the corresponding try is executed, it must also be executed. Finally blocks are usually used to release resources: close files, close socket connections, close database connections, and so on. Examples are as follows: Recommended Reading:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>