Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

try-with-resources

A `try` block that closes opened resources automatically — files, connections, streams.

Available since: Java 7

Syntax

try (Resource r = ...; Resource r2 = ...) {
    ...
} catch (Exception e) {
    ...
}

Examples

The resource is closed even on an exception:

class Connection implements AutoCloseable {
    Connection() { IO.println("open"); }
    void query() { throw new IllegalStateException("query failed"); }
    public void close() { IO.println("close"); }
}
 
void main() {
    try (var conn = new Connection()) {
        conn.query();
    } catch (IllegalStateException e) {
        IO.println("caught: " + e.getMessage());
    }
}

Output:

open
close
caught: query failed

Reading a file line by line:

void main() throws IOException {
    Path file = Files.createTempFile("demo", ".txt");
    Files.writeString(file, "first\nsecond\n");
    try (BufferedReader reader = Files.newBufferedReader(file)) {
        String line;
        while ((line = reader.readLine()) != null) {
            IO.println(line);
        }
    }
    Files.delete(file);
}

Output:

first
second

Notes

The resource must implement AutoCloseable. Several resources are separated by ; and closed in reverse order. close() runs before the catch block. If both the body and close() throw, the exception from close() is not lost: it is available via getSuppressed().

See also

  • try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.
  • AutoCloseable — The interface of a resource that can be closed by try-with-resources.
  • IOException — A checked exception for input and output errors: files, network, data streams.
  • ExecutorService.close() — Closes the pool and waits for all tasks; called automatically by try-with-resources.

Related recipes

In the tutorial

  • try-with-resources — Closing resources automatically in Java — try-with-resources, the AutoCloseable interface, several resources, closing order and suppressed exceptions.

Thanks for reading!

Donate to the site — we work hard for you.