Java Reference
In-Depth Information
9.3
More Programming Techniques for
Exception Handling
Only use this in exceptional circumstances.
WARREN PEACE,
The Lieutenant's Tool
In this section, we present a number of the finer points about programming with
exception handling in Java.
PITFALL: Nested
try-catch
Blocks
You can place a
try
block and its following
catch
blocks inside a larger
try
block
or inside a larger
catch
block. On rare occasions this may be useful, but it is almost
always better to place the inner
try catch
blocks inside a method definition and
place an invocation of the method in the outer
try
or
catch
block (or maybe just
eliminate one or more
try
blocks completely).
If you place a
try
block and its following
catch
blocks inside a larger
catch
block,
you will need to use different names for the
catch
block parameters in the inner and
outer blocks. This has to do with how Java handles nested blocks of any kind. Remem-
ber,
try
blocks and
catch
blocks are blocks.
If you place a
try
block and its following
catch
blocks inside a larger
try
block,
and an exception is thrown in the inner
try
block but is not caught in the inner
catch
blocks, then the exception is thrown to the outer
try
block for processing and might
be caught in one of its
catch
blocks.
■
The
finally
Block
The
finally
block contains code to be executed whether or not an exception is
thrown in a
try
block. The
finally
block, if used, is placed after a
try
block and its
following
catch
blocks. The general syntax is as follows:
★
try
{
...
}
catch
(ExceptionClass1 e)
{
...
}
.
.
.