Search This Blog

Friday 15 August 2014

Finally - JAVA

Finally in Java

After try catch block another block called finally is added. This block runs regardless of exception is thrown or not. Therefore this block is usually used from clean up purposes.


This program shows how to use Finally keyword in Java.

Finally.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Finally {
 public static void main(String args[]){
  FileReader fr = null;
  BufferedReader br = null;
  try {
   fr = new FileReader("myFile.txt");
   br = new BufferedReader(fr);
   String line;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{ //close
   System.out.println("Executing finally ...");
   if (fr != null){
    try {
     fr.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
  System.out.println("Still Alive!");
 }
}

No comments:

Post a Comment