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;
			int c=a/b;
		}catch(ArrayIndexOutOfBounds ae){
			System.out.println("An exception occured: "+ae);
			System.out.println("finally block is executed!");
		System.out.println("Remaining Code...");


Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ExceptionHandling.main(
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