finally Block in Java


Prev Tutorial Next Tutorial

finally Block in Exception Handling

Inside finallyblock we write the block of statements which will relinquish (released or close or terminate) the resource (file or database) where data store permanently.

finally block important points

  • Finally block will execute compulsory
  • Writing finally block is optional.
  • You can write finally block for the entire java program
  • In some of the circumstances one can also write try and catch block in finally block.

Example

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}	
finally
{
System.out.println("I am from finally block");
}
}
}

Output

Denominator not be zero
I am from finally block

Prev Tutorial Next Tutorial

Advertisements
Download Projects