Java Reference
In-Depth Information
Display 9.2
Same Thing Using Exception Handling
(part 3 of 3)
Sample Dialogue 3
Enter number of male dancers:
0
Enter number of female dancers:
5
Lesson is canceled. No men.
Sample Dialogue 4
Enter number of male dancers:
4
Enter number of female dancers:
0
Lesson is canceled. No women.
EXAMPLE:
(continued)
If the number of men or the number of women is zero (or both), that is an exceptional case in
this program and results in an exception being
. To make things concrete, let's say that
the number of men is zero, but the number of women is not zero. In that case the following
statement is executed, which is how Java throws an exception:
thrown
throw new
Exception("Lesson is canceled. No men.");
Let's analyze this statement. The following is the invocation of a constructor for the class
Exception
, which is the standard Java package
java.lang
.
new
Exception("Lesson is canceled. No men.");
The created
Exception
object is not assigned to a variable, but rather is used as an (anonymous)
argument to the
throw
operator. (Anonymous arguments were discussed in Chapter 5.) The key-
word
throw
is an operator with syntax similar to the unary
+
or unary
−
operators. To make it
look more like an operator, you can write it with parentheses around the argument, as follows:
throw
(
new
Exception("Lesson is canceled. No men."));
Although it is perfectly legal and sensible to include these extra parentheses, nobody does
include them.
To understand this process of throwing, you need to know two things: What is this
Exception
class? And what does the
throw
operator do with the
Exception
object? The class
Exception
is another class from the standard Java package
java.lang
. As you have already
seen, the class
Exception
has a constructor that takes a single
String
argument. The
Excep-
tion
object created stores this
String
argument (in a private instance variable). As you will
see, this
String
argument can later be retrieved from the
Exception
object.
(continued)