class ComputeQuotientWithException3
1: //ComputeQuotientWithException3.java:Adapted from Holmes, Chapter 9
2: //Demonstrates creating an arithmetic exception
3: //or a number format exception, and "catching" it.
4: //Uses an alternate formulation from the previous version.
5: //Also illustrates the "instanceof" operator.
7: import java.io.*;
9: class ComputeQuotientWithException3
10: {
11: static BufferedReader keyboard =
12: new BufferedReader(new InputStreamReader(System.in));
13: static PrintWriter screen =
14: new PrintWriter(System.out, true);
16: public static void main(String[] args)
17: {
18: int dividend, divisor, quotient;
19: boolean done = false;
21: do
22: {
23: try
24: {
25: screen.print("\nEnter dividend: ");
26: screen.flush();
27: dividend =
28: new Integer(keyboard.readLine()).intValue();
30: screen.print("Enter divisor: ");
31: screen.flush();
32: divisor =
33: new Integer(keyboard.readLine()).intValue();
35: //Arithmetic exception thrown here
36: //if divisor is zero
37: quotient = dividend/divisor;
38: screen.println("Quotient = " + quotient + "\n");
39: done = true;
40: }
41: catch (Exception e)
42: {
43: if (e instanceof ArithmeticException)
44: screen.println("Exception " + e.toString() +
45: " caught.\nPlease try again ...");
47: else if (e instanceof NumberFormatException)
48: screen.println("Exception " + e.toString() +
49: " caught.\nPlease try again ...");
51: else screen.println("Exception " + e.toString() +
52: " caught.\nPlease try again ...");
53: }
54: }
55: while (!done);
56: }
57: }