Java Reference
In-Depth Information
9.1
Exception Handling Basics
Well the program works for most cases. I didn't know it had to work for
that
case.
COMPUTER SCIENCE STUDENT,
appealing a grade
Exception handling is meant to be used sparingly and in situations that are more
involved than what is reasonable to include in an introductory example. So, we will
teach you the exception handling details of Java by means of simple examples that
would not normally use exception handling. This makes a lot of sense for learning
about the exception handling details of Java, but do not forget that these first examples
are toy examples and, in practice, you would not use exception handling for anything
that simple.
EXAMPLE:
A Toy Example of Exception Handling
Display 9.1 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.2 we have redone the program using exception handling. The keyword
labels a block known as the
, which is indicated in the display. Inside the
try
try
block
block goes the non-exceptional cases and 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
try
statement are the code for throwing the exception:
if-else
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. So, in that case we need not even know what hap-
pens when an exception is “thrown.” If no exception is “thrown,” then the code in the
section labeled “
block” is skipped and the program proceeds to the last statement,
which happens to output
catch
Now, let's see what happens in an
"Begin the lesson."
exceptional case.
(continued)
Search WWH ::




Custom Search