Execution of Finally block


We have created many try-catch-finally block in java code but we do get some doubts regarding certain situations, where finally block will be executed or not

Lets check some of them

Q1. Will finally block be executed even after return statement in try block?

Yes? No? Don't know?

Answer is Yes!

Why?

The code in a finally block will take precedence over the return statement. 

Let's take a look by running the code, to confirm this fact

class SomeClass {
  public static void main(String args[]) {
    // call the proveIt method and print the return value
    System.out.println(SomeClass.proveIt());
  }

  public static int proveIt() {
    try {
      return 1;
    } finally {
      System.out.println("finally block");
    }
  }
}

Let's run the above code
finally block
1

From the above output, we can confirm that the finally block is executed before the control is returned to the calling statement.

Q2: Is there any case when finally block is not executed?

Yes, we have two such scenarios when this will happen:

  1. if System.exit(); is called first
  2. if JVM crashes


Q3: What if there is a return statement in a finally block as well?

In such case, anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block.
Here is an example that will help clarify what we are talking about:
public static int getANumber() {
  try {
    return 7;
  } finally {
    return 28;
  }
}

The code above will actually return 28 instead of the 7, because the return value in the finally block (28) will override the return value in the try block (7).

Also, if the the finally block returns a value, it will override any exception thrown in the try/catch block. Here is an example:
public static int getANumber(){
  try{
    throw new NoSuchFieldException;
  } finally{
    return 28;
  }
}


Previous Post Next Post