[ SNIP ]
Also, remember the difference between checked exceptions and runtime
exceptions. The former are for conditions outside programmer control
(e.g., unavailable resource), and are reported as part of a method's
signature. The latter are for conditions the programmer should have
prevented, such as an illegal argument value. Runtime exceptions are not
part of the method signature; they just take the client code by surprise.
Although in the case of a number of exceptions derived from
RuntimeException, it does make sense to catch them in the calling code.
Because they are not in fact programming errors. For example, consider the
method Integer.parseInt(String). It exists because it's meant to be used,
and it throws a NumberFormatException (which is an unchecked exception). The
only way to avoid throwing an NFE using that method is to validate the
String before you call parseInt, but hell, parseInt is doing precisely that.
So most people I know - myself included - use parseInt (or equivalent
methods) to do the validation, and catch the NFE right then and there.
NumberFormatException is a decent example of an exception which could go
either way. There are really three classes of exceptions:
(a) exceptions that signal recoverable conditions, and you want the calling
code to do something meaningful with it right away. For example,
FileNotFoundException. This is not a programming error if you can't find a
file, you can recover from it, and generally you do want to address the
issue right away. It's a good example of a checked exception;
(b) exceptions that signal situations that cannot be reasonably dealt with.
For example, NullPointerException. This just shouldn't happen. If a method
can return a null, for example, you should have code to deal with it. If you
don't, it's a programming error. It's a good example of an unchecked
(runtime) exception that you don't usually want to catch anywhere;
(c) exceptions that could be recovered from, but you don't necessarily want
to. Consider NumberFormatException again. In some circumstances it's thrown
by a parsing method that has a reasonable expectation of getting a string
which is not a valid number, so it's not a programming error - you catch it
and deal with it. But consider perhaps the case of using it to convert
string values in a flat file, all of which are supposed to be integers (they
were produced by another program)...if one of those strings is not
convertible to an int, maybe you want some discretion as to where in the
calling chain you explicitly handle that NFE, or possibly you don't want to
handle it at all - you want the program run to barf.
For exceptions I myself fall into the middle camp. To a large degree I go
with what Josh Bloch suggests for exceptions, but I also believe that there
are quite a few unchecked exceptions that can in some circumstances be
caught and dealt with (and not treated as programming errors).
AHS