Java Reference
In-Depth Information
9
Exception Handling
It's the exception that proves the rule.
COMMON SAYING
Introduction
One way to divide the task of designing and coding a method is to code two main
cases separately: the case where nothing unusual happens and the case where excep-
tional things happen. Once you have the program working for the case where things
always go smoothly, you can then code the second case where exceptional things can
happen. In Java, there is a way to mirror this approach in your code. You write your
code more or less as if nothing very unusual happens. After that, you use the Java
exception handling facilities to add code for those exceptional cases.
The most important use of exceptions is to deal with methods that have some spe-
cial case that is handled differently depending on how the method is used. For exam-
ple, if there is a division by zero in the method, then it may turn out that for some
invocations of the method the program should end, but for other invocations of the
method something else should happen. Such a method can be defined to throw an
exception if the special case occurs, and that exception will allow the special case to be
handled outside of the method. This allows the special case to be handled differently
for different invocations of the method.
In Java, exception handling proceeds as follows: Either some library software or
your code provides a mechanism that signals when something unusual happens. This
is called
throw
exception
handle
exception
. At another place in your program you place the code
that deals with the exceptional case. This is called
throwing an exception
. This
method of programming makes for cleaner code. Of course, we still need to explain
the details of how you do this in Java.
handling the exception
Prerequisites
Almost all of this chapter only uses material from Chapters 1 through 5 and Chapter
7. The only exception is the subsection “
,” which
also uses material from Chapter 6. However, that subsection may be omitted if you
have not yet covered Chapter 6. Chapter 8 is not needed for this chapter.
ArrayIndexOutOfBoundsException
Search WWH ::




Custom Search