Java Reference
In-Depth Information
Conversely, a method should only catch an exception if it can really remedy the
situation. Otherwise, the best remedy is simply to have the exception propagate to
its caller, allowing it to be caught by a competent handler.
These principles can be summarized with the slogan Ȓthrow early, catch lateȓ.
510
511
Q UALITY T IP 11.2
Do Not Squelch Exceptions
When you call a method that throws a checked exception and you haven't specified
a handler, the compiler complains. In your eagerness to continue your work, it is
an understandable impulse to shut the compiler up by squelching the exception:
try
{
FileReader reader = new FileReader(filename);
// Compiler complained about FileNotFoundException
. . .
}
catch (Exception e) {} // So there!
The do-nothing exception handler fools the compiler into thinking that the
exception has been handled. In the long run, this is clearly a bad idea. Exceptions
were designed to transmit problem reports to a competent handler. Installing an
incompetent handler simply hides an error condition that could be serious.
11.5 The Finally Clause
Occasionally, you need to take some action whether or not an exception is thrown.
The finally construct is used to handle this situation. Here is a typical situation.
It is important to close a PrintWriter to ensure that all output is written to the
file. In the following code segment, we open a writer, call one or more methods, and
then close the writer:
PrintWriter out = new PrintWriter(filename);
writeData(out);
out.close(); // May never get here
Search WWH ::




Custom Search