Java Reference
In-Depth Information
EXAMPLE:
A Toy Example of Exception Handling
Display 9.2 contains a simple program that might, by some stretch of the
imagination, be used at a dance studio. This program does not use exception
handling, and you would not normally use exception handling for anything this
simple. The setting for use of the program is a dance lesson. The program simply
checks to see if there are more men than women or more women than men and
then announces how many partners each man or woman will have. The exceptional
case is when there are no men or no women or both. In that exceptional case, the
dance lesson is canceled.
In Display 9.3, we rewrote the program using exception handling. The
nonexceptional cases go inside the
try
block, and the
try
block checks for the
exceptional cases. The exceptional cases are not handled in the
try
block, but if
detected, they are signaled by throwing an exception. The following three lines taken
from inside the multiway
if-else
statement are the code for throwing the exception:
throw new
Exception("Lesson is canceled. No students.");
throw new
Exception("Lesson is canceled. No men.");
throw new
Exception("Lesson is canceled. No women.");
If the program does not encounter an exceptional case, then none of these
statements that throw an exception is executed. In that case, we need not even know
what happens when an exception is thrown. If no exception is thrown, then the code
in the section labeled “
catch
block” is skipped and the program proceeds to the last
statement, which happens to output
"Begin the lesson."
Now, let's see what
happens in an exceptional case.
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
thrown
. 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:
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 keyword
throw
is an operator with syntax similar to the