9 Best Practices for **java exception handling * *

Source: Internet
Author: User
Tags stack trace throwable

Whether you're a novice or a senior programmer, it's always a good thing to review the practice of exception handling, because it ensures that you and your team can handle it when you're having problems.

Handling Exceptions in Java is not an easy thing to do. Beginners find handling anomalies difficult to understand, and even senior developers spend hours discussing whether throwing exceptions or exceptions should be thrown.

That's why most development teams have their own set of exception handling specifications. If you first enter the team, you may find that these specifications differ greatly from the specifications you used.

Nonetheless, there are some best practice guidelines that are followed by most teams. Here are 9 of the most important practices that can help you get started with exception handling or improve your level of exception handling.

1. Clean up resources in Finally or use Try-with-resource statements

In real-world development, you will often encounter the use of resources in try, such as a inputstream, you need to close it after use. In this case, a common mistake is to close the resource at the tail of the try.

public void Donotcloseresourceintry () {
FileInputStream inputstream = null;
try {
File File = new file ("./tmp.txt");
InputStream = new FileInputStream (file);
Use the InputStream to read a file
Do and do
Inputstream.close ();
} catch (FileNotFoundException e) {
Log.error (e);
} catch (IOException e) {
Log.error (e);
}
}

The problem with this situation is that the program works well as long as the exception is not thrown. All code in the try will be executed normally and the resource will be closed.

However, there is always a reason to use try. When you invoke one or more methods that may throw an exception or throw an exception yourself, the program may not reach the end of the try. So in the end, the resource will not be closed.

Because, you should put all the code that cleans the resource into finally, or use the Try-with-resource statement.

Use Finally
The code in Finally is always executed when the code in the try is executed successfully, or when an exception is handled in the catch, as compared to try. Therefore, you can ensure that all open resources are closed.

public void closeresourceinfinally () {
FileInputStream inputstream = null;
try {
File File = new file ("./tmp.txt");
InputStream = new FileInputStream (file);
Use the InputStream to read a file
} catch (FileNotFoundException e) {
Log.error (e);
} finally {
if (InputStream! = null) {
try {
Inputstream.close ();
} catch (IOException e) {
Log.error (e);
}
}
}
}

Try-with-resource Statements for Java 7

You can also choose the Try-with-resource statement, which is described in more detail in my introduction to Java exception handling.

If you implement the Autocloseable interface in a resource, you can use the Try-with-resource statement, which is also the practice of most Java standard resources. If you open a resource in Try-with-resource, the resource will be automatically closed after the code in the try is executed or the exception is handled.

public void Automaticallycloseresource () {
File File = new file ("./tmp.txt");
Try (fileinputstream InputStream = new FileInputStream (file);) {
Use the InputStream to read a file
} catch (FileNotFoundException e) {
Log.error (e);
} catch (IOException e) {
Log.error (e);
}
}

2. Throw more specific exceptions

The more specific and explicit the exception you throw, the better. Always keep this in mind, especially if you have a colleague who doesn't know your code, or if you need to call your own method and handle the exception after a few months.

Therefore, you need to make sure that you provide as much information as possible, which makes your API easier to understand. This way, the person who calls your method can handle the exception better, thus avoiding additional checks such as this.

Therefore, you should find the class that best matches your exception, such as throwing a numberformatexception instead of illegalargumentexception (note: For example, when you convert a parameter to a numeric error, you should throw a specific NumberFormatException, rather than the general illegalargumentexception). Please avoid throwing a non-specific exception.

public void Donotdothis () throws Exception {
...
}
public void Dothis () throws NumberFormatException {
...
}
3. Write a document for your exception
When you specify an exception in the method signature, you should also record it in the Javadoc.

Therefore, be sure to add @throws declarations in Javadoc and describe situations that may cause exceptions.

/**

    • This method does something extremely useful ...
    • @param input
    • @throws mybusinessexception If ... happens
      */
      public void dosomething (String input) throws Mybusinessexception {
      ...
      }

4. Throw the description information together with the exception

The idea behind this method is similar to the first two. But this time, you don't have to provide information to your method callers. For anyone who encounters an abnormal error and needs to understand the cause of the error, the exception information is always recorded in the log, or printed on the screen, while the exception occurs.

Therefore, be as precise as possible, so it is best not to use throwable in catch unless you can make sure that you are in a certain situation, such as yourself enough to handle the error, or be asked to handle the error. and provide the most relevant information to enable other people to understand what is happening.

Don't get me wrong about what I mean. You don't have to write a large paragraph of text, but you should use one or two short words to explain why the anomaly happened. This will allow your development team to understand the seriousness of the problem and make it easier for you to analyze service incidents.

If you throw a particular exception, its class name probably already describes what type of error it is. So, you don't need to provide a lot of additional descriptive information. A good example of this is that when you provide a String type argument in the wrong format, the Java.lang.Long constructor throws NumberFormatException.

try {
New Long ("XYZ");
} catch (NumberFormatException e) {
Log.error (e);
}
The NumberFormatException class name already tells you the type of problem. So the exception information just needs to return the input string that caused the problem. If the name of the exception class does not indicate its meaning, you will also need to provide the necessary explanatory information in the exception information.

17:17:26,386 ERROR testexceptionhandling:52-java.lang.numberformatexception:for Input string: "XYZ"

5, priority to catch specific exceptions

Most Ides can help you do this. When you try to catch a less specific exception first, the IDE reports to you that this is a block of code that cannot be reached.

The reason for this problem is that only the first catch block that matches to an exception is executed. So, if you catch a illegalargumentexception first, you'll never get to the catch block that handles the more specific exception numberformatexception, because NumberFormatException is I The subclass of the llegalargumentexception.

So, take precedence over more specific exceptions and put less specific catch blocks behind.

Below you can see an example of such a try-catch statement. The first catch handles all numberformatexceptions exceptions, and the second catch handles IllegalArgumentException exceptions other than the numberformatexception exception.

public void Catchmostspecificexceptionfirst () {
try {
DoSomething ("A message");
} catch (NumberFormatException e) {
Log.error (e);
} catch (IllegalArgumentException e) {
Log.error (e)
}
}

6. Do not capture Throwable

Throwable is the parent class for all exceptions and errors. Although you can use it in a catch clause, you should never do so!

If you use throwable in a catch clause, it will not only catch all exceptions, it will also catch all errors. These errors are thrown by the JVM to indicate a serious error that is not intended to be handled by the application. OutOfMemoryError and Stackoverflowerror are typical examples, both of which are caused by situations beyond the scope of application control and cannot be processed.

Therefore, it is best not to use throwable in catch unless you can make sure that you are in a certain situation, such as yourself enough to handle the error, or be asked to handle the error.

public void donotcatchthrowable () {
try {
Do something
} catch (Throwable t) {
Don ' t do this!
}
}

7. Do not ignore exceptions

Have you analyzed a bug report that only the first part of the use case was executed?

This is usually caused by ignoring the exception. The developer may be quite certain that the exception will not be thrown, and then add a catch that cannot be handled or cannot be logged. When you find this catch, you are likely to find such a famous remark: "This will never happen".

public void Donotignoreexceptions () {
try {
Do something
} catch (NumberFormatException e) {
This would never happen
}
}

Yes, you may be analyzing a problem that will never happen.

So, make sure you don't ignore exceptions. You don't know what changes the code will undergo in the future. Some people may mistakenly delete the validation of unusual events without realizing that this will produce a problem at all. Or the code that throws the exception is modified, the same class is thrown with multiple exceptions, and the code that calls them does not prevent these exceptions from occurring.

At a minimum, you should print out the log information and tell those unconscious of the wrong operation that they need to check here.

public void Loganexception () {
try {
Do something
} catch (NumberFormatException e) {
Log.error ("This should never happen:" + e);
}
}

8. Do not print and throw exceptions at the same time

This is probably one of the most commonly overlooked practice guidelines in this article. You can find this problem in many code snippets or even libraries, where exceptions are caught, printed, and re-thrown.

try {
New Long ("XYZ");
} catch (NumberFormatException e) {
Log.error (e);
Throw e;
}

This may be intuitive to see the printed exception, the exception is re-thrown, the caller will be able to handle it very well. However, this will cause multiple error messages to be printed with the same exception.

17:44:28,945 ERROR testexceptionhandling:65-java.lang.numberformatexception:for Input string: "XYZ"
Exception in thread "main" Java.lang.NumberFormatException:For input string: "XYZ"
At Java.lang.NumberFormatException.forInputString (numberformatexception.java:65)
At Java.lang.Long.parseLong (long.java:589)
At Java.lang.Long. (long.java:965)
At Com.stackify.example.TestExceptionHandling.logAndThrowException (testexceptionhandling.java:63)
At Com.stackify.example.TestExceptionHandling.main (testexceptionhandling.java:58)

Additional information is not available to provide more error details. As described in rule 4th, the exception information should accurately describe the exception event. Stack trace will tell you which class, which method, and which row the exception is thrown in.

If you need to add additional information, you should catch the exception and wrap it in a custom exception, but be sure to follow the 9th practice guidelines below.

public void Wrapexception (String input) throws Mybusinessexception {
try {
Do something
} catch (NumberFormatException e) {
throw new Mybusinessexception ("A message that describes the error.", e);
}
}

So, just catch it when you want to handle an exception. Otherwise, it would be nice to indicate the exception to the caller's attention at the method signature.

9. Package exception but do not discard the original exception

Sometimes wrapping an exception as a custom exception is better than catching a standard exception. A typical example is a specific business exception for an application or framework. This allows you to add additional information, and also to implement a specific processing method for your exception class.

When you do this, make sure that the original exception is set to cause. The Exception class provides a series of specific construction methods that can accept Throwable as parameters (Note: Exception (String message, throwable cause)). Otherwise, you will lose the stack trace and information of the original exception, which can make it difficult to analyze the event that caused the exception.

public void Wrapexception (String input) throws Mybusinessexception {
try {
Do something
} catch (NumberFormatException e) {
throw new Mybusinessexception ("A message that describes the error.", e);
}
}

Summarize
As you can see, when deciding whether to throw or catch an exception, you need to think about many things. Most of the practice guidelines above are designed to improve the readability and usability of your code and APIs.

Exception is not only an error handling mechanism, but also a communication medium. Therefore, you should discuss with your colleagues what best practices and guidelines you want to apply so that everyone can understand the underlying concepts and apply them in the same way in practice

9 Best Practices for **java exception handling * *

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.