Skip to content
Veltoryx Technologies
ProLesson 5.3Intermediate2 min readUpdated 30 October 2026

try-with-resources

Close files, connections and streams automatically and safely with try-with-resources, and learn what AutoCloseable and suppressed exceptions are.

Files, database connections, network sockets and streams are resources: they must be closed when you're done, or your program slowly runs out of them. Closing them correctly by hand is surprisingly hard. try-with-resources (Java 7) does it for you.

01The old way, and why it's error-prone

java
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("data.txt"));
    System.out.println(reader.readLine());
} catch (IOException e) {
    System.out.println("Read failed");
} finally {
    if (reader != null) {
        try { reader.close(); } catch (IOException e) { /* and now? */ }
    }
}

Lots of code, an easy-to-forget null check, and an awkward nested try just to close.

Loading the rest of the lesson…