Java Reference
In-Depth Information
// This block contains statements that handle an exception object
// of type SomeException or a subclass of that type. Statements in
// this block can refer to that exception object by the name e1.
}
catch ( AnotherException | YetAnotherException e2 ) {
// This block contains statements that handle an exception of
// type AnotherException or YetAnotherException, or a subclass of
// either of those types. Statements in this block refer to the
// exception object they receive by the name e2.
}
finally {
// This block contains statements that are always executed
// after we leave the try clause, regardless of whether we leave it:
// 1) normally, after reaching the bottom of the block;
// 2) because of a break, continue, or return statement;
// 3) with an exception that is handled by a catch clause above;
// 4) with an uncaught exception that has not been handled.
// If the try clause calls System.exit(), however, the interpreter
// exits before the finally clause can be run.
}
try
The try clause simply establishes a block of code that either has its exceptions han‐
dled or needs special cleanup code to be run when it terminates for any reason. The
try clause by itself doesn't do anything interesting; it is the catch and finally clau‐
ses that do the exception-handling and cleanup operations.
catch
A try block can be followed by zero or more catch clauses that specify code to han‐
dle various types of exceptions. Each catch clause is declared with a single argu‐
ment that specifies the types of exceptions the clause can handle (possibly using the
special | syntax to indicate that the catch block can handle more than one type of
exception) and also provides a name the clause can use to refer to the exception
object it is currently handling. Any type that a catch block wishes to handle must be
some subclass of Throwable .
When an exception is thrown, the Java interpreter looks for a catch clause with an
argument that matches the same type as the exception object or a superclass of that
type. The interpreter invokes the first such catch clause it finds. The code within a
catch block should take whatever action is necessary to cope with the exceptional
condition. If the exception is a java.io.FileNotFoundException exception, for
example, you might handle it by asking the user to check his spelling and try again.
It is not required to have a catch clause for every possible exception; in some cases,
the correct response is to allow the exception to propagate up and be caught by the
invoking method. In other cases, such as a programming error signaled by Null
PointerException , the correct response is probably not to catch the exception at
Search WWH ::




Custom Search