Java Reference
In-Depth Information
Display 9.9
Use of a throws Clause (part 2 of 2)
13
double quotient = safeDivide(numerator, denominator);
14
System.out.println(numerator + "/"
15
+ denominator
16
+ " = " + quotient);
17
}
18
catch (DivisionByZeroException e)
19
{
20
System.out.println(e.getMessage());
21
secondChance();
22
}
23
24
System.out.println("End of program.");
25
}
26
27
public static double safeDivide( int top, int bottom)
28
throws DivisionByZeroException
29
{
30
if (bottom == 0)
31
throw new DivisionByZeroException();
32
return top/( double )bottom;
33
}
34
public static void secondChance()
35
{
36
Scanner keyboard = new Scanner(System.in);
37
38
try
39
{
40
System.out.println("Enter numerator:");
41
int numerator = keyboard.nextInt();
42
System.out.println("Enter denominator:");
43
int denominator = keyboard.nextInt();
44
double quotient = safeDivide(numerator, denominator);
45
System.out.println(numerator + "/"
46
+ denominator
47
+ " = " + quotient);
48
}
49
catch (DivisionByZeroException e)
50
{
51
System.out.println("I cannot do division by zero.");
52
System.out.println("Aborting program.");
53
System.exit(0);
54
}
The input/output dialogues are
identical to those for the program in
Display 9.4.
55
}
56
}
Search WWH ::




Custom Search