Java Reference
In-Depth Information
Display 9.8 Catching Multiple Exceptions (part 2 of 3)
8
try
9
{
10
System.out.println("How many pencils do you have?");
11
int pencils = keyboard.nextInt();
12
if (pencils < 0)
13
throw new NegativeNumberException("pencils");
14
System.out.println("How many erasers do you have?");
15
int erasers = keyboard.nextInt();
16
double pencilsPerEraser;
17
if (erasers < 0)
18
throw new NegativeNumberException("erasers");
19
else if (erasers != 0)
20
pencilsPerEraser = pencils/( double )erasers;
21
else
22
throw new DivisionByZeroException();
23
System.out.println("Each eraser must last through "
24
+ pencilsPerEraser + " pencils.");
25
}
26
catch (NegativeNumberException e)
27
{
28
System.out.println("Cannot have a negative number of "
29
+ e.getMessage());
30
}
31
catch (DivisionByZeroException e)
32
{
33
System.out.println("Do not make any mistakes.");
34
}
35
System.out.println("End of program.");
36
}
37
}
Sample Dialogue 1
How many pencils do you have?
5
How many erasers do you have?
2
Each eraser must last through 2.5 pencils
End of program.
(continued)
Search WWH ::




Custom Search