Java Reference
In-Depth Information
only the method
main
.) There are three possibilities when the code in the
try-catch-
finally
blocks is run:
1. The
try
block runs to the end and no exception is thrown. In this case, the
finally
block is executed after the
try
block.
2. 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.
3. 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
27. Can you have a
try
block and corresponding
catch
blocks inside another larger
try
block?
28. Can you have a
try
block and corresponding
catch
blocks inside another larger
catch
block?
29. What is the output produced by the following program? What would the out-
put 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);
}
catch
(Exception e)
{
System.out.println("Caught in main.");
}
}
public static void
exerciseMethod(
int
n)
throws
Exception
{
try
{
if
(n > 0)
throw new
Exception();
else if
(n < 0)
throw new
NegativeNumberException();