A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block. catch clauses and a finally clause are often unnecessary when resources are closed automatically.
TryWithResourcesStatement:
try ResourceSpecification Block [Catches] [Finally]
ResourceSpecification:
( ResourceList [;] )
ResourceList:
Resource {; Resource}
Resource:
LocalVariableDeclaration
VariableAccess
VariableAccess:
ExpressionName
FieldAccess
The following productions from §4.3, §8.3, §8.4.1, and §14.4 are shown here for convenience:
LocalVariableDeclaration:
{VariableModifier} LocalVariableType VariableDeclaratorList
VariableModifier:
Annotation
final
LocalVariableType:
UnannType
var
VariableDeclaratorList:
VariableDeclarator {, VariableDeclarator}
VariableDeclarator:
VariableDeclaratorId [= VariableInitializer]
VariableDeclaratorId:
Identifier [Dims]
Dims:
{Annotation} [ ] {{Annotation} [ ]}
VariableInitializer:
Expression
ArrayInitializer
See §8.3 for UnannType.
The resource specification denotes the resources of the try-with-resources statement, either by declaring local variables with initializer expressions or by referring to existing variables. An existing variable is referred to by an expression name (§6.5.6) or a field access expression (§15.11).
The rules for a local variable declared in a resource specification are specified in §14.4. In addition, all of the following must be true, or a compile-time error occurs:
- The VariableDeclaratorList consists of a single VariableDeclarator.
- The VariableDeclarator has an initializer.
- The VariableDeclaratorId has no bracket pairs.
The scope and shadowing of a local variable declared in a resource specification is specified in §6.3 and §6.4.
References to the local variable from a nested class or interface, or a lambda expression, are restricted, as specified in §6.5.6.1.
The type of a local variable declared in a resource specification is specified in §14.4.1.
The type of a local variable declared in a resource specification, or the type of an existing variable referred to in a resource specification, must be a subtype of AutoCloseable, or a compile-time error occurs.
It is a compile-time error for a resource specification to declare two local variables with the same name.
Resources are final, in that:
- A local variable declared in a resource specification is implicitly declared
finalif it is not explicitly declaredfinal(§4.12.4). - An existing variable referred to in a resource specification must be a
finalor effectivelyfinalvariable that is definitely assigned before thetry-with-resources statement (§16 (Definite Assignment)), or a compile-time error occurs.
Resources are initialized in left-to-right order. If a resource fails to initialize (that is, its initializer expression throws an exception), then all resources initialized so far by the try-with-resources statement are closed. If all resources initialize successfully, the try block executes as normal and then all non-null resources of the try-with-resources statement are closed.
Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.
A try-with-resources statement whose resource specification indicates multiple resources is treated as if it were multiple try-with-resources statements, each of which has a resource specification that indicates a single resource. When a try-with-resources statement with n resources (n > 1) is translated, the result is a try-with-resources statement with n-1 resources. After n such translations, there are n nested try-catch-finally statements, and the overall translation is complete.
14.20.3.1. Basic try-with-resources
A try-with-resources statement with no catch clauses or finally clause is called a basic try-with-resources statement.
If a basic try-with-resource statement is of the form:
try (VariableAccess ...)
Block
then the resource is first converted to a local variable declaration by the following translation:
try (T #r = VariableAccess ...) {
Block
}
T is the type of the variable denoted by VariableAccess and #r is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the try-with-resources statement occurs. The try-with-resources statement is then translated according to the rest of this section.
The meaning of a basic try-with-resources statement of the form:
try ({VariableModifier} R Identifier = Expression ...)
Block
is given by the following translation to a local variable declaration and a try-catch-finally statement:
{
final {VariableModifierNoFinal} R Identifier = Expression;
Throwable #primaryExc = null;
try ResourceSpecification_tail
Block
catch (Throwable #t) {
#primaryExc = #t;
throw #t;
} finally {
if (Identifier != null) {
if (#primaryExc != null) {
try {
Identifier.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
Identifier.close();
}
}
}
}
{VariableModifierNoFinal} is defined as {VariableModifier} without final, if present.
#t, #primaryExc, and #suppressedExc are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the try-with-resources statement occurs.
If the resource specification indicates one resource, then ResourceSpecification_tail is empty (and the try-catch-finally statement is not itself a try-with-resources statement).
If the resource specification indicates n > 1 resources, then ResourceSpecification_tail consists of the 2nd, 3rd, ..., n'th resources indicated in the resource specification, in the same order (and the try-catch-finally statement is itself a try-with-resources statement).
Reachability and definite assignment rules for the basic try-with-resources statement are implicitly specified by the translation above.
In a basic try-with-resources statement that manages a single resource:
-
If the initialization of the resource completes abruptly because of a
throwof a valueV, then thetry-with-resources statement completes abruptly because of athrowof the valueV. -
If the initialization of the resource completes normally, and the
tryblock completes abruptly because of athrowof a valueV, then:- If the automatic closing of the resource completes normally, then the
try-with-resources statement completes abruptly because of athrowof the valueV. - If the automatic closing of the resource completes abruptly because of a
throwof a valueV2, then thetry-with-resources statement completes abruptly because of athrowof valueVwithV2added to the suppressed exception list ofV.
- If the automatic closing of the resource completes normally, then the
-
If the initialization of the resource completes normally, and the
tryblock completes normally, and the automatic closing of the resource completes abruptly because of athrowof a valueV, then thetry-with-resources statement completes abruptly because of athrowof the valueV.
In a basic try-with-resources statement that manages multiple resources:
-
If the initialization of a resource completes abruptly because of a
throwof a valueV, then:- If the automatic closings of all successfully initialized resources (possibly zero) complete normally, then the
try-with-resources statement completes abruptly because of athrowof the valueV. - If the automatic closings of all successfully initialized resources (possibly zero) complete abruptly because of
throws of valuesV1...Vn, then thetry-with-resources statement completes abruptly because of athrowof the valueVwith any remaining valuesV1...Vnadded to the suppressed exception list ofV.
- If the automatic closings of all successfully initialized resources (possibly zero) complete normally, then the
-
If the initialization of all resources completes normally, and the
tryblock completes abruptly because of athrowof a valueV, then:- If the automatic closings of all initialized resources complete normally, then the
try-with-resources statement completes abruptly because of athrowof the valueV. - If the automatic closings of one or more initialized resources complete abruptly because of
throws of valuesV1...Vn, then thetry-with-resources statement completes abruptly because of athrowof the valueVwith any remaining valuesV1...Vnadded to the suppressed exception list ofV.
- If the automatic closings of all initialized resources complete normally, then the
-
If the initialization of every resource completes normally, and the
tryblock completes normally, then:- If one automatic closing of an initialized resource completes abruptly because of a
throwof valueV, and all other automatic closings of initialized resources complete normally, then thetry-with-resources statement completes abruptly because of athrowof the valueV. - If more than one automatic closing of an initialized resource completes abruptly because of
throws of valuesV1...Vn, then thetry-with-resources statement completes abruptly because of athrowof the valueV1with any remaining valuesV2...Vnadded to the suppressed exception list ofV1(whereV1is the exception from the rightmost resource failing to close andVnis the exception from the leftmost resource failing to close).
- If one automatic closing of an initialized resource completes abruptly because of a
14.20.3.2. Extended try-with-resources
A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.
The meaning of an extended try-with-resources statement:
try ResourceSpecification
Block
[Catches]
[Finally]
is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:
try {
try ResourceSpecification
Block
}
[Catches]
[Finally]
The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.
Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.