Java Reference
In-Depth Information
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)
{
...
}
.
.
.
catch (ExceptionClassLast e)
{
...
}
finally
{
< Code to be executed whether or not an exception is thrown or caught. >
}
Now, suppose that the try-catch-finally blocks are inside a method definition.
(After all, every set of try-catch-finally blocks is inside of some method, even if it is
Search WWH ::




Custom Search