EMZETT.
Login

try-with-resources

In short: A language construct that ensures an opened resource (file, database connection, network socket) is automatically closed again — even if an exception occurs in the meantime.

In more detail: Without this construct, closing a resource has to be done manually in a finally block, which is easily forgotten and leads to resource leaks (e.g. a file that stays open even though the program is done with it). try-with-resources takes over automatic cleanup for any resource that implements the appropriate “closeable” behaviour.

In Depth

Before try-with-resources (or in languages without this construct), every resource had to be closed manually in a finally block — and even this supposedly safe approach has its own pitfall:

// The "old", error-prone way
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("file.txt"));
    System.out.println(reader.readLine());
} finally {
    if (reader != null) {
        reader.close();   // has to be manually checked and called
    }
}

With try-with-resources, this reduces to a single, significantly less error-prone line:

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    System.out.println(reader.readLine());
}   // reader.close() is called automatically HERE - even on an exception

The decisive advantage shows up once several resources are open at the same time: with the manual finally approach, each one has to be closed individually and in the correct (reverse) order, which quickly makes the code cluttered. try-with-resources allows several resources simply separated by semicolons in the same parentheses, and reliably takes care of correctly, completely closing all of them — even if an error already occurs while opening the second resource, the first is still closed cleanly.

For a resource to be usable in try-with-resources, it has to implement a specific “closeable” behaviour (in Java, the AutoCloseable interface) — this is why the construct doesn’t work for arbitrary objects, only for those explicitly marked as “a resource that has to be closed”.

See also: Exceptions, Files