Java Reference
In-Depth Information
Ask the Expert
Q
:
Why would I want to catch superclass exceptions?
A
:
There are, of course, a variety of reasons. Here are a couple. First, if you add a
catch
clause that catches exceptions of type
Exception
, then you have effectively added a
“catch all” clause to your exception handler that deals with all program-related ex-
ceptions. Such a “catch all” clause might be useful in a situation in which abnormal
program termination must be avoided no matter what occurs. Second, in some situ-
ations, an entire category of exceptions can be handled by the same clause. Catching
the superclass of these exceptions allows you to handle all without duplicated code.
In this case,
catch(Throwable)
catches all exceptions except for
ArrayIn-
dexOutOfBounds
-
Exception
. The issue of catching subclass exceptions becomes more
important when you create exceptions of your own.
Try Blocks Can Be Nested
One
try
block can be nested within another. An exception generated within the inner
try
block that is not caught by a
catch
associated with that
try
is propagated to the outer
try
block. For example, here the
ArrayIndexOutOfBoundsException
is not caught by the in-
ner
catch
, but by the outer
catch
: