finally block in Java

  • A finally block is used to write code that must be executed irrespective of whether the code throws an exception or not.
  • In this block, you define cleanup code that is code that releases and closes resources.
  • If catch block(s) exists, then you cannot write finally block before a catch block(s).
  • A try block without a catch block is valid, if it has a finally block.
  • You cannot write try, catch, and finally blocks independently.

Example showing the use of finally keyword

public class ExceptionHandling{
	public static void main(String args[]){
		int a=25, b=0;
		try{
			int c=a/b;
			System.out.println("c="+c);
		}catch(ArrayIndexOutOfBounds ae){
			System.out.println("An exception occured: "+ae);
		}finally{
			System.out.println("finally block is executed!");
		}
		System.out.println("Remaining Code...");
	}
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ExceptionHandling.main(ExceptionHandling.java:5)
finally block is executed!

Situation when finally block does not execute

There are certain conditions in which a finally block does not execute-

  • The try or catch block writes System.exit statement that ends the application.
  • Fatal errors occur in the JVM or OS