Java Reference
In-Depth Information
On the other hand, some applications will not be able to recover from certain con‐
ditions—even conditions that are theoretically modelled by checked exceptions. For
example, if an application requires a config file to be placed at a specific place in the
filesystem and is unable to locate it at startup, there may be very little it can do
except print an error message and exit—despite the fact that java.io.FileNotFoun
dException is a checked exception. Forcing exceptions that cannot be recovered
from to be either handled or propagated is, in these circumstances, bordering on
perverse.
When designing exception schemes, there are some good practices that you should
follow:
• Consider what additional state needs to be placed on the exception—remember
that it's also an object like any other.
Exception has four public constructors—under normal circumstances, custom
exception classes should implement all of them—to initialize the additional
state, or to customize messages.
• Don't create many fine-grained custom exception classes in your APIs—the
Java I/O and reflection APIs both suffer from this and it needlessly complicates
working with those packages.
• Don't overburden a single exception type with describing too many conditions
—for example, the Nashorn JavaScript implementation (new with Java 8) origi‐
nally had overly coarse-grained exceptions, although this was fixed before
release.
Finally, two exception handling antipatterns that you should avoid:
// Never just swallow an exception
try {
someMethodThatMightThrow ();
} catch ( Exception e ){
}
// Never catch, log and rethrow an exception
try {
someMethodThatMightThrow ();
} catch ( SpecificException e ){
log ( e );
throw e ;
}
The former of these two just ignores a condition that almost certainly required
some action (even if just a notification in a log). This increases the likelihood of fail‐
ure elsewhere in the system—potentially far from the original, real source.
The second one just creates noise—we're logging a message but not actually doing
anything about the issue—we still require some other code higher up in the system
to actually deal with the problem.
Search WWH ::




Custom Search