Java Reference
In-Depth Information
9
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 exceptional
things happen. Once you have the program working for the case where things always
go smoothly, you can then code the second case where notable things can happen. In
Java, there is a way to mirror this approach in your code. Write your code more or less
as if nothing very unusual happens. After that, use the Java exception handling facilities
to add code for those unusual cases.
The most important use of exceptions is to deal with methods that have some
special case that is handled differently depending on how the method is used. For
example, 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; that exception will permit 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 throwing an exception . At another place in your program, you place the
code that deals with the exceptional case. This is called handling the 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.
throw
exception
handle
exception
Prerequisites
Almost this entire chapter uses only material from Chapters 1 through 5 and Chapter 7 .
The only exception is the subsection “ ArrayIndexOutOfBoundsException ,” 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.
 
Search WWH ::




Custom Search