Java Finally Block


ava finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block must be followed by try or catch block.


Why use java finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Syntax

try{  
//code that may throw exception  
} 
 finally
 {  
   //Statement
    }

Example

 class finally_block
{
 public static void main(String[] args)
 {
  int a[]= new int[3];
  try 
  {
   System.out.println("Access invalid element"+ a[5]);
 /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally 
  {
   System.out.println("finally is always executed.");
  }
 }
}
Output
finally is always executed.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Share this article on