Java Reference
In-Depth Information
statement, which is described in the next section. The Java interpreter first looks at
the enclosing block of code to see if it has an associated exception handler. If so, it
exits that block of code and starts running the exception-handling code associated
with the block. After running the exception handler, the interpreter continues exe‐
cution at the statement immediately following the handler code.
If the enclosing block of code does not have an appropriate exception handler, the
interpreter checks the next higher enclosing block of code in the method. This con‐
tinues until a handler is found. If the method does not contain an exception handler
that can handle the exception thrown by the
throw
statement, the interpreter stops
running the current method and returns to the caller. Now the interpreter starts
looking for an exception handler in the blocks of code of the calling method. In this
way, exceptions propagate up through the lexical structure of Java methods, up the
call stack of the Java interpreter. If the exception is never caught, it propagates all the
way up to the
main()
method of the program. If it is not handled in that method,
the Java interpreter prints an error message, prints a stack trace to indicate where
the exception occurred, and then exits.
a
x
The try/catch/inally Statement
Java has two slightly different exception-handling mechanisms. The classic form is
the
try/catch/finally
statement. The
try
clause of this statement establishes a
block of code for exception handling. This
try
block is followed by zero or more
catch
clauses, each of which is a block of statements designed to handle specific
exceptions. Each catch block can handle more than one different exception—to
indicate that a catch block should handle multiple exceptions, we use the
|
symbol
to separate the different exceptions a catch block should handle. The
catch
clauses
are followed by an optional
finally
block that contains cleanup code guaranteed to
be executed regardless of what happens in the
try
block.
try Block Syntax
Both the
catch
and
finally
clauses are optional, but every
try
block must be
accompanied by at least one or the other. The
try
,
catch
, and
finally
blocks all
begin and end with curly braces. These are a required part of the syntax and cannot
be omitted, even if the clause contains only a single statement.
The following code illustrates the syntax and purpose of the
try/catch/finally
statement:
try
{
// Normally this code runs from the top of the block to the bottom
// without problems. But it can sometimes throw an exception,
// either directly with a throw statement or indirectly by calling
// a method that throws an exception.
}
catch
(
SomeException
e1
)
{