Java Reference
In-Depth Information
Q: Why does an exception make that situation a better design?
A: Because I cannot ignore an exception if it is a checked exception.
If the withdraw() method throws an InsufficientFundsException, I
must try to handle it every time I invoke withdraw(). Sure, I can do
nothing once I catch the exception, and keep spending money I
don't have, but I can no longer plead ignorance to the bank and
say that I had no idea I was overdrawn. Just as interfaces can be
used to force behavior on a class, the Handle or Declare Rule can
be used to force callers of a method to deal with potential prob-
lems and not simply ignore them.
The throws Keyword
Let's revisit the Lazy class that did not handle nor declare the two exceptions.
From a design point of view, the readOneByte() method should probably not
catch the exceptions anyway; otherwise, the caller of the method does not
know what happened or is not given a chance to fix any problems. Therefore,
the readOneByte() method should declare the exceptions, which is done using
the throws keyword:
public byte readOneByte() throws FileNotFoundException, IOException
The following NotSoLazy class fixes the compiler errors of the Lazy class by
declaring the exceptions.
import java.io.*;
public class NotSoLazy
{
public byte readOneByte() throws FileNotFoundException, IOException
{
//Same as before
}
//Remainder of class definition
}
Because FileNotFoundException is a child class of IOException, the
readOneByte() method can declare just the IOException:
public byte readOneByte() throws IOException
A method that invokes readOneByte() can still try to catch the
FileNotFoundException and IOException separately or try to catch
just the IOException.
Search WWH ::




Custom Search