Java Reference
In-Depth Information
that a nonexistent element is being accessed, but it does not have enough information
to decide what to do about this failure. Should the user be asked to try a different
operation? Should the program be aborted after saving the user's work? The logic for
these decisions is contained in a different part of the program code.
In Java, exception handling provides a flexible mechanism for passing control from
the point of error reporting to a competent recovery handler. In the remainder of this
chapter, we will look into the details of this mechanism.
When you detect an error condition, your job is really easy. You just throw an
appropriate exception object, and you are done. For example, suppose someone tries
to withdraw too much money from a bank account.
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
// Now what?
. . .
}
. . .
}
First look for an appropriate exception class. The Java library provides many classes
to signal all sorts of exceptional conditions. Figure 1 shows the most useful ones.
To signal an exceptional condition, use the throw statement to throw an
exception object.
Look around for an exception type that might describe your situation. How about the
IllegalStateException ? Is the bank account in an illegal state for the
withdraw operation? Not reallyȌsome withdraw operations could succeed. Is
the parameter value illegal? Indeed it is. It is just too large. Therefore, let's throw an
illegalArgumentException . (The term argument is an alternative term for a
parameter value.)
503
Search WWH ::




Custom Search