Wednesday, May 16, 2018

CoreJava 0n Java finally block


Java 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 handles or not.

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

For each try block, there can be zero or more catch blocks, but only one finally block

The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).                                                      Ref - https://teck4world.blogspot.com/2018/05/systemexitint-x.html


Case 01 - The exception doesn't occur.


  1. class TestFinallyBlock{  
  2.   public static void main(String args[]){  
  3.   try{  
  4.    int data=25/5;  
  5.    System.out.println(data);  
  6.   }  
  7.   catch(NullPointerException e){System.out.println(e);}  
  8.   finally{System.out.println("finally block is always executed");}  
  9.   System.out.println("rest of the code...");  
  10.   }  
  11. }  



Case 02 - The exception occurs and not handled.


  1. class TestFinallyBlock1{  
  2.   public static void main(String args[]){  
  3.   try{  
  4.    int data=25/0;  
  5.    System.out.println(data);  
  6.   }  
  7.   catch(NullPointerException e){System.out.println(e);}  
  8.   finally{System.out.println("finally block is always executed");}  
  9.   System.out.println("rest of the code...");  
  10.   }  
  11.  
Case 03 - The exception occurs and handled.

  1. public class TestFinallyBlock2{  
  2.   public static void main(String args[]){  
  3.   try{  
  4.    int data=25/0;  
  5.    System.out.println(data);  
  6.   }  
  7.   catch(ArithmeticException e){System.out.println(e);}  
  8.   finally{System.out.println("finally block is always executed");}  
  9.   System.out.println("rest of the code...");  
  10.   }  
  11. }  

No comments:

Post a Comment