Source of TwoCatchesDemo.java


  2: import java.util.Scanner;

  4: public class TwoCatchesDemo
  5: {
  6:    public static void main(String[] args)
  7:    {
  8:       try
  9:       {
 10:          System.out.println("Enter number of widgets produced:");
 11:          Scanner keyboard = new Scanner(System.in);
 12:          int widgets = keyboard.nextInt( );
 13:          if (widgets < 0)
 14:              throw new NegativeNumberException("widgets");

 16:          System.out.println("How many were defective?");
 17:          int defective = keyboard.nextInt( );
 18:          if (defective < 0)
 19:              throw new NegativeNumberException("defective widgets");

 21:          double ratio = exceptionalDivision(widgets, defective);
 22:          System.out.println("One in every  " + ratio +
 23:                                                         " widgets is defective.");
 24:       }
 25:       catch(DivideByZeroException e)
 26:       {
 27:          System.out.println("Congratulations! A perfect record!");
 28:       }
 29:       catch(NegativeNumberException e)
 30:       {
 31:          System.out.println("Cannot have a negative number of " +
 32:                                                          e.getMessage( ));
 33:       }
 34:       System.out.println("End of program.");
 35:    }

 37:    public static double exceptionalDivision(double numerator, double denominator)
 38:                         throws DivideByZeroException

 40:    {
 41:        if (denominator == 0)
 42:              throw new DivideByZeroException( );
 43:        return numerator / denominator;
 44:    }
 45: }