Source of TwoCatchesDemo.java


  1: 
  2: import java.util.*;
  3: 
  4: public class TwoCatchesDemo
  5: {
  6:    public static void main(String[] args)
  7:    {
  8:       try
  9:       {
 10:          int widgets, defective;
 11:          double ratio;
 12: 
 13:          System.out.println("Enter number of widgets produced:");
 14:          Scanner keyboard = new Scanner(System.in);
 15:          widgets = keyboard.nextInt( );
 16:          if (widgets < 0)
 17:              throw new NegativeNumberException("widgets");
 18: 
 19:          System.out.println("How many were defective?");
 20:          defective = keyboard.nextInt( );
 21:          if (defective < 0)
 22:              throw new NegativeNumberException("defective widgets");
 23: 
 24:          ratio = exceptionalDivision(widgets, defective);
 25:          System.out.println( "One in every  " + ratio
 26:                                     + " widgets is defective.");
 27:       }
 28:       catch(DivideByZeroException e)
 29:       {
 30:          System.out.println("Congratulations! A perfect record!");
 31:       }
 32:       catch(NegativeNumberException e)
 33:       {
 34:          System.out.println("Cannot have a negative number of "
 35:                              + e.getMessage( ));
 36:       }
 37:       System.out.println("End of program.");
 38:    }
 39: 
 40:    public static double exceptionalDivision(double numerator,
 41:                    double denominator) throws DivideByZeroException
 42: 
 43:    {
 44:        if (denominator == 0)
 45:              throw new DivideByZeroException( );
 46:        return (numerator/denominator);
 47:    }
 48: }