The finally block

The finally keyword creates a block of code that will be executed after a trycatch block has completed and before the code following the try-catch block. After a catch block has been executed, control is always transferred to the finally block, if one is specified. This is always true as long as there is a finally block, regardless of whether the catch block itself throws an exception. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try-catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing our files, releasing our network sockets or database connections, performing any other cleanup our code requires. The finally clause is optional. However, each try statement requires at least one catch or a finally clause. Even If, there is a return statement in the try block, the finally block executes right after the return statement.

 

Rules for try, catch and finally blocks

1.  For each try block there can be zero or more catch blocks, but only one finally block.  

2.  The catch blocks and finally block must always appear in conjunction with a try block. 

3.  A try block must be followed by either at least one catch block or one finally block.

4.  The order of exception handlers in catch block must be from the most specific exception. 

 

Here is the general form of an exception-handling try-catch-finally block:

try {
   // block of code that generates an exception
}
catch (Exception-Type1 e1) {
    // block of code that handles the exception for Exception-Type1
}
catch (Exception-Type2 e2) {
   // block of code that handles the exception for Exception-Type2
}
. . .
. . .
finally { // finally is optional
  // it will always execute whether or not an exception is thrown
}
// Exception-Type is the type of exception that has occurred.

 

The following program (Except10.java) demonstrates how finally works:

public class Except10 {

// throwing an exception out of the method
static void methodA() {
    try {
      System.out.println("We are inside methodA()");
      throw new RuntimeException("Test");
   }
    finally {
      System.out.println("The methodA()'s finally block executes");
    }
}

// returning from within a try block
  static void methodB() {
    try {
     System.out.println("We are inside methodB()");
      return;
    }
    finally {
      System.out.println("The methodB()'s finally block executes");
    }
  }

// executing a try block normally
static void methodC() {
   try {
     System.out.println("We are inside methodC()");
   }
   finally {
     System.out.println("The methodC()'s finally block executes");
   }
  }

public static void main(String a[]) {
   try {
     methodA();
  }
   catch (Exception e) {
     System.out.println("Exception caught in main = "+e);
  }
   methodB();
  methodC();
}

}

 Output:      

We are inside methodA()
The methodA()'s finally block executes
Exception caught in main = java.lang.RuntimeException: Test
We are inside methodB()
The methodB()'s finally block executes
We are inside methodC()
The methodC()'s finally block executes

 

Explanation:      

In the above program, methodA( ) prematurely breaks out of the try block by throwing an exception. The finally clause is executed on the way out. The methodB( )’s try statement is exited via a return statement. The finally clause is executed before methodB( ) returns. In methodC( ), the try statement executes normally, without error. However, the finally block is still executed.