Java Reference
In-Depth Information
Catching Subclass Exceptions
If a
catch
handler is written to catch
superclass
exception objects, it can also catch all objects
of that class's
subclasses
. This enables
catch
to handle related exceptions
polymorphically
.
You can catch each subclass individually if those exceptions require different processing.
Only the First Matching
catch
Executes
If
multiple
catch
blocks match a particular exception type, only the
first
matching
catch
block executes when an exception of that type occurs. It's a compilation error to catch the
exact same type
in two different
catch
blocks associated with a particular
try
block. How-
ever, there can be several
catch
blocks that match an exception—i.e., several
catch
blocks
whose types are the same as the exception type or a superclass of that type. For instance,
we could follow a
catch
block for type
ArithmeticException
with a
catch
block for type
Exception
—both would match
ArithmeticException
s, but only the first matching
catch
block would execute.
Common Programming Error 11.3
Placing a
catch
block for a superclass exception type before other
catch
blocks that catch
subclass exception types would prevent those
catch
blocks from executing, so a compilation
error occurs.
Error-Prevention Tip 11.3
Catching subclass types individually is subject to error if you forget to test for one or more
of the subclass types explicitly; catching the superclass guarantees that objects of all sub-
classes will be caught. Positioning a
catch
block for the superclass type after all other sub-
class
catch
blocks ensures that all subclass exceptions are eventually caught.
Software Engineering Observation 11.7
In industry, throwing or catching type
Exception
is discouraged—we use it here simply
to demonstrate exception-handling mechanics. In subsequent chapters, we generally throw
and catch more specific exception types.
Programs that obtain certain resources must return them to the system to avoid so-called
resource leaks
.
In programming languages such as C and C++, the most common resource
leak is a
memory leak
. Java performs automatic
garbage collection
of memory no longer used
by programs, thus avoiding most memory leaks. However, other types of resource leaks can
occur. For example, files, database connections and network connections that are not closed
properly after they're no longer needed might not be available for use in other programs.
Error-Prevention Tip 11.4
A subtle issue is that Java does not entirely eliminate memory leaks. Java will not garbage-
collect an object until there are no remaining references to it. Thus, if you erroneously keep
references to unwanted objects, memory leaks can occur.
The
finally
block (which consists of the
finally
keyword, followed by code
enclosed in curly braces), sometimes referred to as the
finally
clause
, is optional. If it's