Exception Handling Best Practices in Java

In this post some of the exception handling best practices in Java are listed. Following these best practices in your Java code will help you in writing robust code.

Java Exception handling best practices

1- Don’t ignore exception– Exception handling especially the checked exception gives you a chance to recover from the thrown exception. Thus having a catch block that is empty defeats the very purpose of exception handling.

You need to avoid code like this –

Even if you are pretty sure that there won’t be any exception in the block of code, still log the error at least. In the rare case exception is thrown in the block at least you will be having some log message to find out what went wrong.

2- Always clean up resources in finally block– If you are using resources like I/O streams, DB connection, socket connection in your code ensure that you close them in finally block.
Closing them with in the try block may work fine if there is no exception. If there is any exception thrown in the try block and the normal flow is disrupted, code for closing the resources may never get executed. To avoid that always close the resources in finally block as finally block is always executed whether error is thrown or not.

Java 7 onward you can also use try-with-resource statement for ensuring resources clean up. Using try-with-resource will make your code shorter too.

3- Don’t use parent class as “catch all” solution – Using parent class like Throawble, Exception or RunTimeException as a generic exception handler is not a good practice.
You should always try to throw the specific exception class that can be thrown from the code block. That makes your code more readable.
You should throw specific exception-

Not generic “catch all” exception.

You should not catch Throwable like this.

Throwable is the superclass of all errors and exceptions in Java. Catching Throwable means you are catching errors too from which you can’t recover from like OutOfMemoryError, StackOverFlowError. Which is against the recommended approach that application should not try and recover from Errors such as these.

4- Throw early or fail fast– One of the exception handling best practices in Java is to throw early. By throwing an exception early (also known as “failing fast”), the exception becomes both more specific and more accurate. The stack trace immediately shows what went wrong.

The exception stack trace helps pinpoint where an exception occurred by showing us the exact sequence of method calls that lead to the exception, along with the class name, method name, source code filename, and line number for each of these method calls.

Now let’s see an example

Output

If you scan the stack trace it looks like there is some problem with the open() method of the FileInputStream class. In the code you can see that real problem is passing space as file name. So checking that condition immediately in the method you can throw an exception early.

Changed Java program with file name check condition

Output

Now the exception message is more precise.

5-Catch late– A common mistake is to catch an exception before the program can handle it in an appropriate manner. For checked exceptions, Java compiler enforces that exception either be caught or declared. The natural tendency is to immediately wrap the code in a try block and catch the exception to stop the compile time errors.

Output

The above code catches FileNotFoundException, when it really cannot do anything to recover from the error. If the file is not found, the rest of the method certainly cannot read from the file.
Calling the code with the file that doesn’t exist will result in FileNotFoundException getting logged and then the program tries to read data from the file.
Since the file doesn’t exist, in is null, and a NullPointerException gets thrown.

The way to pass responsibility for handling exceptions further up the call chain is to declare the exception in the throws clause of the method. When declaring which exceptions may be thrown, remember to be as specific as possible.
With these changes the code would look like as follows.

6- Document the thrown exceptions – Document the exceptions, which are declared in the method signature, in Javadoc. For that use @throws in your Javadoc specifying the exception and the possible cause when that exception can be thrown.

7- Don’t use exception for flow control– When an exception is thrown whole process creating an exception object, going through the method stack to look for the exception handler that can handle the thrown exception is followed. So try to use this exception handling mechanism for exceptional conditions only.
Using exception handling as flow control tool means slowing the performance of your application for simple things that can easily be checked with conditional statements.
Use if condition for checking –

Rather than this –

8- Don’t Log and throw – Doing both logging as well as rethrowing an exception is an anti-pattern and not a good practice. It adds multiple error messages in your log for the same exception.

Output

As you can see in the output you have multiple error messages for the same exception.

9- Java exception handling slows the overall performance– When an exception is thrown in your code an exception object is created and the method stack is searched for the appropriate exception handler. This slows the overall performance of your application so use exception handling mechanism for exceptional conditions.
Where you can avoid exception handling by doing some conditional checking do that rather than using try-catch block. Some of this is already discussed in point 7 “Don’t use exception for flow control”.

10 – Include the original exception– If you are throwing another exception after catching the original exception, as per the exception handling best practices in Java you should ensure that original exception is not lost.
Use the constructor with the cause parameter to retain the original exception.

11- Convert layer specific exception– If an exception is thrown in any layer of your application which is specific to that layer ensure that you wrap it in different exception. This practice helps with loose coupling where implementation of any specific layer is kept abstracted from another layer.
As example- In DAOLayer you may have to catch SQLException but that should not be propagated to another layer. You can wrap it into another exception and throw it.

That’s all for the topic Exception Handling Best Practices in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: Java Program to Compress File in gzip Format in Hadoop - KnpCode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.