Friday, February 13, 2015

Finally

Finally is a block of code which would be executed irrespective of the exception exist or not, generally it is known as the clean up code, it is used to close the database connection if open etc.

package Example1;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionAgain {
 static Scanner scanobj=new Scanner(System.in);
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("how old are you");
  int age=checktheage();
  if(age!=0){
   System.out.println(" you are "+age+" old");
  }
 }

 public static int checktheage(){
  try{
   return scanobj.nextInt();
  }
  catch(InputMismatchException e){
   System.out.println("Do not enter whole number");
   return 0;
  }
  finally{
   System.out.println("clean up code");
  }
 }
}


>>>
------------------------------------------------------------------------------------------------------------