These are the times that try men's souls.
Thomas Paine, The American Crisis (1780)
. . . and they all fell to playing the game of catch as catch can,
till the gunpowder ran out at the heels of their boots.
Samuel Foote
A try statement executes a block. If a value is thrown and the try statement has
one or more catch clauses that can catch it, then control will be transferred to the
first such catch clause. If the try statement has a finally clause, then another
block of code is executed, no matter whether the try block completes normally or
abruptly, and no matter whether a catch clause is first given control.
TryStatement:
tryBlockCatches
tryBlockCatchesoptFinally Catches:
CatchClause
CatchesCatchClause CatchClause:
catch (FormalParameter)Block Finally:
finallyBlock
The following is repeated from §8.4.1 to make the presentation here clearer:
FormalParameter:
TypeVariableDeclaratorId
The following is repeated from §8.3 to make the presentation here clearer:
VariableDeclaratorId:
Identifier
VariableDeclaratorId[ ]
The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.
A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause. An exception parameter must not have the same name as a local variable or parameter in whose scope it is declared, or a compile-time error occurs.
The scope of the name of an exception parameter is the Block of the catch clause. The name of the parameter may not be redeclared as a local variable or exception parameter within the Block of the catch clause; that is, hiding the name of an exception parameter is not permitted.
Exception parameters cannot be referred to using qualified names (§6.6), only by simple names.
Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object.
A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately.