Java Reference
In-Depth Information
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 only the method
main
.) There are three possibilities when the code in the
try-
catch-finally
blocks is run:
• The
try
block runs to the end and no exception is thrown. In this case, the
finally
block is executed after the
try
block.
• An exception is thrown in the
try
block and is caught in one of the
catch
blocks
positioned after the
try
block. In this case, the
finally
block is executed after the
catch
block is executed.
• An exception is thrown in the
try
block and there is no matching
catch
block in
the method to catch the exception. In this case, the method invocation ends and the
exception object is thrown to the enclosing method. However, the
finally
block
is executed before the method ends. Note that you cannot account for this last case
simply by placing code after the
catch
blocks.
Self-Test Exercises
29. Can you have a
try
block and corresponding
catch
blocks inside another
larger
try
block?
30. Can you have a
try
block and corresponding
catch
blocks inside another
larger
catch
block?
31. What is the output produced by the following program? What would the
output be if the argument to
exerciseMethod
were
−42
instead of
42
? (The
class
NegativeNumberException
is defined in Display 9.8, but you need not
review that definition to do this exercise.)
public class
FinallyDemo
{
public static void
main(String[] args)
{
try
{
exerciseMethod(42);
}
(continued)