9 considerations for handling exceptions in java

abnormal:

Checked exception (compile-time exception: try catch or statement throw)
unchecked exception (run-time exception: for example: except 0 exception, the default rollback in the transaction is "unchecked exception")

1. Clean up the resources in the Finally block, or use the Try-With-Resource statement

It often happens when using resources in try blocks, such as InputStreams, that need to be closed after use. A common mistake that occurs is closing the resource at the end of the try block:
write picture description here
if all goes well, as long as no exception is thrown, this approach seems to work just fine, all statements in the try are executed, and the resource is also closed .
However, if you add a try for some reason, one or more of the methods called may cause an exception, or even you may cause an exception yourself. At this time, you cannot run to the end of the try, and as a result, the resource cannot be closed. Lose.
Therefore, you should put all code that cleans up resources in a finally block, or use a Try-With-Resource statement.

  • use finally block

Unlike the last few lines in the try, the finally block is always executed, whether after the try block is successfully executed or the exception is handled in the catch block. This way, you can be sure to clear all open resources.
write picture description here

  • Try-With-Resource Statement in Java 7

Another way is to use the Try-With-Resource statement.
You can use this statement if the resource you are using implements the interface AutoCloseable, as most Java standard resources do. When you open a resource in a try, it can automatically close the resource after the try is executed or after the exception is handled.
write picture description here

2. Try to use specific exceptions

The more specific the exception you raise, the better. Always keep in mind those peers who don't know your code, or you in a few months, who need to call your methods to handle exceptions.
So, try to provide as much information as possible to make sure your API is easier to understand. This way, the person calling your method can better handle exceptions or avoid wasting extra time on checks.
To find a way to find the class that best suits the event you expect, such as throwing a NumberFormatException is better than IllegalArguementException, avoid throwing an ambiguous exception.
write picture description here

3. Record the specified exception in the method comment (Javadoc)

Whenever you specify an exception in your method signature, you should document it in your Javadoc. This has the same purpose as the previous one, which is to give the caller as much information as possible so that they can avoid or handle exceptions.
So, make sure you add the @throws statement to your Javadoc, explaining what conditions will throw an exception.
write picture description here

4. Use a descriptive message to briefly describe the exception thrown

This one is similar to the idea behind the first two, except this time there is no need to provide any information to the method caller. Because when an exception is reported in the log file or in the monitor, everyone has to read the exception message.
Therefore, you should describe the problem as accurately as possible and provide the most relevant information to help understand the anomaly.
Please don't get me wrong, I'm not asking you to write a long paragraph. You should explain the exception in a sentence or two. This will help your operations team understand the severity of the problem, and it will also make it easier for you to analyze service exceptions.
If you throw a particular exception, its class name probably already describes the type of error, so you don't have to provide any more information. A good example is NumberFormatException, which is thrown by the constructor of class java.lang.Long when you are supplying the wrong format for a string.
write picture description here
NumberFormatException, the name already tells you the problem, you just need to provide the string that caused the problem. If the name of the exception class is not expressive, provide the required information in the message.
write picture description here

5. Catch the most specific exceptions first

Most IDEs can help you do this. They report an unreachable block of code when you're trying to catch less specific exceptions preferentially.
The problem is that only the first catch block that matches the exception gets executed, and if you catch the IllegalArgumentException first, you can't get to the more specific NumberFormatException that should be handled, because NumberFormatException is a subclass of it.
Always catch the most specific exception class first, and add a lower precision catch block to the end of the list.
In the following code snippet, you can see an example of such a try-catch statement. The first catch block handles all NumberFormatExceptions, and the second handles all IllegalArgumentExceptions that are not NumberFormatExceptions.
write picture description here

6. Don't catch throwable objects

Throwable is the superclass of all exceptions and errors, and while you can use it in catch statements, you should never use it.
If you use throwables in a catch statement, the result is not just catching all exceptions, it catches all errors as well. Errors are thrown by the JVM and indicate serious problems that are not intended to be handled by the application. Representative examples of this type are OutOfMemoryError, and StackOverflowError, both of which are raised by situations outside the application's control and cannot be handled.
So, don't catch throwables unless you're absolutely sure you're in an exceptional situation and you're capable or required to handle the error.
write picture description here

7. Don’t ignore exceptions

Have you ever analyzed a bug report where only the first part of the use case was executed?
The cause of this is often an overlooked exception, and the developer was probably pretty sure it wouldn't be thrown again, and added a Catch blocks that cannot handle or log exceptions. Then, when you find this block, you also have a good chance of finding a famous comment called "Never Happens".
write picture description here
It is certainly possible that you are analyzing an impossible problem.
So, don't ignore an exception. You don't know how your code will change in the future, maybe someone will remove the validation you used to prevent exceptions, completely unaware that this will cause problems. Or, the code that throws the exception is modified so that multiple exceptions are thrown in the same class, and the calling code can no longer prevent all exceptions.
write picture description here
You should at least write a log message telling everyone that something unimaginable happened and someone needs to check.

8. Don’t record and throw again

This one is probably the most overlooked on this list. However, you can always find lots of code snippets and even libraries where exceptions are caught, logged and then thrown.
write picture description here
The general intuition is that logging an exception when it occurs and then throwing it will make it easier for the caller to handle the exception properly. The problem is that people often write multiple error messages for the same exception.
write picture description here
And the post-added message doesn't have any other information. We said in Item 4 that the exception message should describe the exception event. Then the stack trace will tell you which class threw the exception, which method and which line.
If you need to add more information, you should catch the exception and wrap it in a custom message. But be sure to follow Article 9.
write picture description here
So, catch it only when you want to handle the exception. Otherwise specify it in the method signature and let the caller handle it.

9. Pack it without depleting the exception

Sometimes it's better to catch a standard exception and wrap it in a custom exception. Typically application or framework specific business exceptions, you can add additional information and perform special handling for exception classes.
In doing so, make sure to set the original exception as the cause (the exception class provides a special constructor that accepts a throwable object as a parameter). If you don't do this, the original exception's stack trace and message will be lost, making the exception's event difficult to analyze.
write picture description here

Summarize

As you can see, there are a lot of different things you should consider when you throw or catch exceptions, most of which are to improve code readability or API usability.
Exceptions are usually caused by a faulty handling mechanism and the communication medium used at the same time. Therefore, you should discuss with your colleagues the practices and rules you are going to use, so that everyone understands the common concepts, and then enforce those practices and rules in the same way.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325954101&siteId=291194637