In Java, what does the finally block do?

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like this:

public void someMethod{
   Try {
   // some code

   Catch(Exception x) {
   // some code

   Catch(ExceptionClass y) {
   // some code

   //this code will be executed whether or not an exception 
   //is thrown or caught

There are 4 potential scenarios here:

1.	The try block runs to the end, and no exception is 
thrown.  In this scenario, the finally block will be 
executed after the try block.

2.	An exception is thrown in the try block, which is
then caught in one of the catch blocks.  In this scenario, 
the finally block will execute right after the catch block 

3.	An exception is thrown in the try block and there's 
no matching catch block in the method that can catch 
the exception.  In this scenario, the call to the method 
ends, and the exception object   is thrown to the enclosing 
method - as in the method in which the   try-catch-finally
blocks reside.  But, before the method ends, the finally 
block is executed.

4.  Before the try block runs to completion it returns to 
wherever the method was invoked.  But, before it returns 
to the invoking method, the code in the finally block is still 
executed.  So, remember that the code in the finally  block 
willstill be executed even if there is a return 
statement somewhere in the try block.

You can also read more about how the finally block will run after a return statement here – along with some good code samples: Will finally run after return?

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

3 thoughts on “Finally block”