Java finally block

finally block in java is used to execute important code such as closing database connection, file connection, etc. Java finally block is executed in every circumstances whether exception occurs or not or even exception is handled or not.

Syntax of finally block

try { statement 1; }
finally { statement 2; }

Note: finally block must be preceded by try or catch block.

Internal working of java finally block

In every case finally block gets executed whether exception occurs or not or whether exception is handled or not

Let’s us discuss implementation of finally block one by one. According to the above diagram finally block can be discussed onto three grounds. They are as under:

  1. Exception do not occurs still finally block gets executed
  2. Exception occurs but it is not handled still finally block gets executed
  3. Exception occurs and is handled executing the finally block

Case 1. Exception do not occurs still finally block gets executed

class Finally1 {
public static void main(String args[]) { System.out.println("Welcome students"); try { int a=55/5; } catch(Exception e) { System.out.println(e); } finally { System.out.println("I am finally block"); System.out.println("I will execute in every case"); }
System.out.println("Rest of the code"); }
}

Output:

Explanation: In the above program exception do not occurs that’s why every statements of the program are executed including finally block.

Case 2. Exception occurs but it is not handled still finally block gets executed

class Finally2 {
public static void main(String args[]) { System.out.println("Welcome students"); try { int a=55/0; // ArithmeticException occurs } catch(NullPointerException e) // ArithmeticException not handled { System.out.println(e); } finally { System.out.println("I am finally block"); System.out.println("I will execute in every case"); }
System.out.println("Rest of the code"); }
}

Output:

Explanation: In the above program “Rest of the code” is not printed because exception which occurs is not handled still finally block gets executed. See the above program carefully where ArithmeticException occurs (i.e. int a=55/0;) but in catch block instead of handling ArithmeticException, NullPointerException is being handled to show the use of finally block for the above said situation.

Case 3. Exception occurs and is handled executing the finally block

class Finally3 {
public static void main(String args[]) { System.out.println("Welcome students"); try { int a=55/0; } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("I am finally block"); System.out.println("I will execute in every case"); }
System.out.println("Rest of the code"); }
}

Output:

Explanation: In the above program we have discussed the 3rd case of the finally block where every statements of the program has been executed including finally block.