---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 8 Edition"
java_version: 8
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/se8/html/jls-14.html#jls-14.20.3
id: "14.20.3"
url: https://jvm.obfuscated.software/jls/se8/14.20.3.html
raw: https://jvm.obfuscated.software/jls/se8/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
```

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:
  (one of)
  Annotation final

VariableDeclaratorId:
  Identifier [Dims]

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

A *resource specification* declares one or more local variables with initializer expressions to act as *resources* for the `try` statement.

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` ([§4.12.4](4.12.4.md)) if it is not explicitly declared `final`.

The type of a variable declared 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 declares multiple resources is treated as if it were multiple `try`-with-resources statements, each of which has a resource specification that declares 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.

The meaning of a basic `try`-with-resources statement:

```
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 declares 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 declares *n* > 1 resources, then *ResourceSpecification_tail* consists of the 2nd, 3rd, ..., *n*'th resources declared in 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.
