Finally Block in Java

Introduction

 
It is a special block in Java. It is a block in a program that always executes. If we want to perform an important task and want it to execute always in any condition then we use a finally block in Java.
 

Finally, Block in Java

 
The following describes the finally block in Java:
  • In Java, finally is a special keyword.
  • It always executes independently of any condition. 
  • It is optional in Java. 
  • It should be after the try-catch block in Java. 
  • For a single try block, there can be a maximum of one finally block in Java. 
  • Generally, we use a finally for closing the connections or closing the file and so on.
     
    finally always executes
     

Examples of Finally in Java

 

No Exception Condition

  1. package demo;  
  2. public class Demo {  
  3.  public static void main(String args[]) {  
  4.   try {  
  5.    int fig = 36 / 6;  
  6.    System.out.println(fig);  
  7.   } catch (NullPointerException e) {  
  8.    System.out.println(e);  
  9.   } finally {  
  10.    System.out.println("ALWAYS EXECUTE");  
  11.   }  
  12.   System.out.println("#**.......**#");  
  13.  }  
  14. }  
Output
when no exception
 

Exception Condition

  1. package test;  
  2. public class Test {  
  3.  public static void main(String args[]) {  
  4.   try {  
  5.    int fig = 36 / 0;  
  6.    System.out.println(fig);  
  7.   } catch (NullPointerException e) {  
  8.    System.out.println(e);  
  9.   } finally {  
  10.    System.out.println("ALWAYS EXECUTE");  
  11.   }  
  12.   System.out.println("#**.......**#");  
  13.  }  
  14. }  
Output
when exception
 

Exception Condition, But Handled

  1. package trial;  
  2. public class Trial {  
  3.  public static void main(String args[]) {  
  4.   try {  
  5.    int fig = 36 / 0;  
  6.    System.out.println(fig);  
  7.   } catch (ArithmeticException e) {  
  8.    System.out.println(e);  
  9.   } finally {  
  10.    System.out.println("ALWAYS EXECUTE");  
  11.   }  
  12.   System.out.println("#**.......**#");  
  13.  }  
  14. }  
Output
exception but handled

Summary

 
This article has explained the finally block in Java.


Similar Articles