Sunday, October 21, 2012

Java program to illustrate exception handling


import java.lang.ArithmeticException;
import java.util.*;                                //import util package
public class ExceptionDemo
{  public static void main(String s[])
  {   Scanner b1=new Scanner(System.in);
    try
     {  System.out.println("Enter the Divident?");
        double a=b1.nextDouble();
        System.out.println("Enter the Divisor?");
        double b=b1.nextDouble();
      if(b==0)
  //Throwing an Exception using throw
       throw new ArithmeticException("Division by zero!");
       double res=a/b;
       System.out.println("Result of"+a+"/"+b+"is"+res);
     }
  //Handles input mismatch exception caused by
 //entering a non-integer value at th point
  catch(InputMismatchException e)
       {  System.out.println("Error:"+e);}
//Handles the divide-by-zero ArithmeticException
  catch(ArithmeticException ae)
      {  System.out.println("Error:"+ae);}
   }
}
Output

0 comments:

Post a Comment