Java Reference
In-Depth Information
Display 9.3
Same Thing Using Exception Handling
(part 2 of 3)
9
System.out.println("Enter number of female dancers:");
10
int
women = keyboard.nextInt();
This is just a toy example to learn Java syntax. Do not take it
as an example of good typical use of exception handling.
11
try
12
{
13
if
(men == 0 && women == 0)
14
throw new
Exception("Lesson is canceled. No students.");
15
else
if
(men == 0)
16
throw new
Exception("Lesson is canceled. No men.");
17
else
if
(women == 0)
try
block
18
throw new
Exception("Lesson is canceled. No women.");
19
// women >= 0 && men >= 0
20
if
(women >= men)
21
System.out.println("Each man must dance with " +
22
women/(
double
)men + " women.");
23
else
24
System.out.println("Each woman must dance with " +
25
men/(
double
)women + " men.");
26
}
27
catch
(Exception e)
28
{
29
String message = e.getMessage();
catch
block
30
System.out.println(message);
31
System.exit(0);
32
}
33
System.out.println("Begin the lesson.");
34
}
35
}
Sample Dialogue 1
Enter number of male dancers:
4
Enter number of female dancers:
6
Each man must dance with 1.5 women.
Begin the lesson.
Sample Dialogue 2
Enter number of male dancers:
0
Enter number of female dancers:
0
Lesson is canceled. No students.
Note that this dialogue and
the dialogues below do not
say
"Begin the lesson"
.