Finally Block in Java

When an exception is thrown in a code the normal execution flow of the method is disrupted and that may result in opened resources never getting closed. In such scenarios you do need a clean up mechanism that’s where finally block in Java helps.

As Example – Suppose in a method you open a file and start reading it using input stream. Some exception happened in between and the code to close the stream is never executed. By using finally block and keeping the code to close the stream in that finally block you can ensure that the code to close the stream is always executed.

Finally block

Finally block in Java exception handling can immediately follow the try block making it a try-finally block or you can have a full try-catch-finally block. Try block must be followed by either catch or finally of course you can have both too making it a full try-catch-finally block.

Finally block in Java always executes whether exception is thrown in try block or not. In case no exception is thrown inside the try block, finally block is executed when try block exists.

When exception is thrown in a try block if there is a catch block that matches the exception type of the thrown exception that catch block is executed first and then the finally block.
In case catch block can’t handle the thrown exception finally block is still executed just before the method returns.

Finally block Java example code

Let’s try to see these scenarios with example Java programs-

When catch block is there and handles the thrown exception

Output

When catch block is there but doesn’t handle the thrown exception

In catch block Exception type is changed to NullPointerExcpetion where as exception thrown is ArithmeticException. Finally block is still executed and then the exception is propagated to be handled by default handler in this case.

Output

What happens if the exception is thrown in the finally block

If code enclosed in try block throws an exception and the finally block also throws an exception then exception thrown by finally clause masks the exception thrown in try block.

Let’s see an example to clarify it. Suppose you have a code to read a file and the file that is passed doesn’t exist at the gievn path. In that case FileNotFoundException will be thrown from the try block. You also have a finally block where you have a code to close the BufferedReader object but that is null in this case so finally block is also going to throw NullPointerException.

Output

That’s why you should avoid throwing exception in the finally clause. In the above code you can have an if condition checking for null to avoid NullPointerException at least.

Finally block with return

Even if there is a return statement in try block and no exception is thrown in try block, finally block will still be executed before the method returns.

Example code

Output

If you have a return statement in finally clause also then the value returned by try statement is replaced by the value returned by the finally block. Moreover it will also suppress any exception thrown from the try block. That is why there should not be any return statement in finally block. Use the finally block for what it is intended to do clean up code.

Example code

If we take the example code as used above and place a return statement in finally block then that value will be returned. Also note that there is an attempt to divide by zero but that exception is suppressed.

Output

If you comment the return statement in finally block and then run the program you can see the exception.

When is Java finally block not executed

Though finally block will always be executed whether any exception is thrown in try block or not. But, there are certain scenarios when finally block in Java is not executed.

If the JVM exits while the try or catch code is being executed (System.exit() or JVM crash), then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Important points

  1. Finally block in Java is used to clean up code. You should put the code to close opened resources (input stream ,output stream, opened DB connection) in finally block.
  2. Though finally block is optional but try block must immediately be followed by either catch or finally block. You can have a full try-catch-finally block too.
  3. Finally block is always executed whether try block exits without any exception or because of an exception.
  4. Only time finally block is not executed is when JVM exits or the thread executing the try or catch code is interrupted or killed.
  5. If finally block throws an exception that will mask the exception thrown in try block.
  6. If there is a return statement in finally block that is the value returned.
  7. Having a return statement in finally block may suppress the thrown exception so there should not be a return statement in finally block.

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


You may also like

3 Comments

  1. Pingback: try-with-resources in Java - KnpCode

  2. Pingback: Exception Handling Best Practices in Java - KnpCode

  3. Pingback: finalize() Method in Java - 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.