Source of ComputeQuotientWithException2.java


  1: //ComputeQuotientWithException2.java:Adapted from Holmes, Chapter 9
  2: //Demonstrates creating an arithmetic exception
  3: //or a number format exception, and "catching" it.

  5: import java.io.*;

  7: class ComputeQuotientWithException2
  8: {
  9:     static BufferedReader keyboard =
 10:         new BufferedReader(new InputStreamReader(System.in));
 11:     static PrintWriter screen =
 12:         new PrintWriter(System.out, true);

 14:     public static void main(String[] args)
 15:     throws IOException
 16:     {
 17:         int dividend, divisor, quotient;
 18:         boolean done = false;

 20:         do
 21:         {
 22:             try
 23:             {
 24:                 screen.print("\nEnter dividend: ");
 25:                 screen.flush();
 26:                 dividend =
 27:                     new Integer(keyboard.readLine()).intValue();

 29:                 screen.print("Enter divisor: ");
 30:                 screen.flush();
 31:                 divisor =
 32:                     new Integer(keyboard.readLine()).intValue();

 34:                 //Arithmetic exception thrown here
 35:                 //if divisor is zero
 36:                 quotient = dividend/divisor;
 37:                 screen.println("Quotient = " + quotient + "\n");
 38:                 done = true;
 39:             }
 40:             catch (ArithmeticException arithException)
 41:             {
 42:                 screen.println("Exception " +
 43:                                arithException.toString() +
 44:                                " caught.\nPlease try again ...");
 45:             }
 46:             catch (NumberFormatException numFormException)
 47:             {
 48:                 screen.println("Exception " +
 49:                                numFormException.toString() +
 50:                                " caught.\nPlease try again ...");
 51:             }
 52:         }
 53:         while (!done);
 54:     }
 55: }