---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 9 Edition"
java_version: 9
chapter: "Chapter 14. Blocks and Statements"
section: "14.20.3"
heading: "14.20.3. try-with-resources"
parent: "14.20. The try statement"
source: https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.20.3
id: "14.20.3"
url: https://jvm.obfuscated.software/jls/se9/14.20.3.html
raw: https://jvm.obfuscated.software/jls/se9/14.20.3.md
---

# 14.20.3. `try`-with-resources

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:
  {VariableModifier} UnannType VariableDeclaratorId = Expression
  VariableAccess

VariableAccess:
  ExpressionName
  FieldAccess
```

See [§8.3](8.3.md) for *UnannType*. The following productions from [§4.3](4.3.md), [§8.3](8.3.md), and [§8.4.1](8.4.1.md) are shown here for convenience:

```
VariableModifier:
  Annotation
  final

VariableDeclaratorId:
  Identifier [Dims]

Dims:
  {Annotation} [ ] {{Annotation} [ ]}
```

A *resource specification* uses variables to denote *resources* for the `try` statement, either by declaring local variables with initializer expressions or by referring to suitable existing variables. An existing variable is referred to by either an expression name ([§6.5.6](6.5.6.md)) or a field access expression ([§15.11](15.11.md)).

It is a compile-time error for a resource specification to declare two variables with the same name.

It is a compile-time error if `final` appears more than once as a modifier for each variable declared in a resource specification.

A variable declared in a resource specification is implicitly declared `final` if it is not explicitly declared `final` ([§4.12.4](4.12.4.md)).

A resource denoted by an expression name or field access expression must be a `final` or effectively `final` variable that is definitely assigned before the `try`-with-resources statement ([§16 (*Definite Assignment*)](16.md)), or a compile-time error occurs.

The type of a variable declared or referred to as a resource in a resource specification must be a subtype of `AutoCloseable`, or a compile-time error occurs.

The scope and shadowing of a variable declared in a resource specification is specified in [§6.3](6.3.md) and [§6.4](6.4.md).

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 `throw` of a value `V`, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.

- If the initialization of the resource completes normally, and the `try` block completes abruptly because of a `throw` of a value `V`, then:

  - If the automatic closing of the resource completes normally, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.
  - If the automatic closing of the resource completes abruptly because of a `throw` of a value `V2`, then the `try`-with-resources statement completes abruptly because of a `throw` of value `V` with `V2` added to the suppressed exception list of `V`.

- If the initialization of the resource completes normally, and the `try` block completes normally, and the automatic closing of the resource completes abruptly because of a `throw` of a value `V`, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.

In a basic `try`-with-resources statement that manages multiple resources:

- If the initialization of a resource completes abruptly because of a `throw` of a value `V`, then:

  - If the automatic closings of all successfully initialized resources (possibly zero) complete normally, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.
  - If the automatic closings of all successfully initialized resources (possibly zero) complete abruptly because of `throw`s of values `V1`...`Vn`, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V` with any remaining values `V1`...`Vn` added to the suppressed exception list of `V`.

- If the initialization of all resources completes normally, and the `try` block completes abruptly because of a `throw` of a value `V`, then:

  - If the automatic closings of all initialized resources complete normally, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.
  - If the automatic closings of one or more initialized resources complete abruptly because of `throw`s of values `V1`...`Vn`, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V` with any remaining values `V1`...`Vn` added to the suppressed exception list of `V`.

- If the initialization of every resource completes normally, and the `try` block completes normally, then:

  - If one automatic closing of an initialized resource completes abruptly because of a `throw` of value `V`, and all other automatic closings of initialized resources complete normally, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V`.
  - If more than one automatic closing of an initialized resource completes abruptly because of `throw`s of values `V1`...`Vn`, then the `try`-with-resources statement completes abruptly because of a `throw` of the value `V1` with any remaining values `V2`...`Vn` added to the suppressed exception list of `V1` (where `V1` is the exception from the rightmost resource failing to close and `Vn` is the exception from the leftmost resource failing to close).

## 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.
