Library contents

Java Try-with-resources

Open a reader in the parentheses after try. Java closes it when the block finishes, including when reading or processing throws an exception.

A simple example

Try-with-resources

  1. Start with An open reader containing A
  2. Do this Read inside a resource block
  3. Result A, then reader closed
Leaving the block closes the reader, including when the body exits early.

Syntax

Java syntax
try (BufferedReader reader = Files.newBufferedReader(path)) { /* read lines */ }
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read a final line without a newline

A line-based import may include a blank record or a last record without a terminating newline. Distinguish a legitimate line from the end of the input so the import keeps the right number of rows.

First output line[A]
Main.java
import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (var rows = new BufferedReader(new StringReader("A\n\nB"))) {
            for (String row; (row = rows.readLine()) != null; ) {
                System.out.println("[" + row + "]");
            }
        }
    }
}
Output
[A]
[]
[B]

This in-memory reader uses the same try-with-resources syntax as a file reader. The middle line is blank, the final line has no newline, and the reader closes when the block ends.

Advertisements

Keep the original scanner failure on close

A stock scanner can fail while decoding an item and again while closing its connection. Support needs the original read failure and the cleanup failure together to diagnose the shift.

First output lineRead failed
Main.java
import java.io.IOException;

class Main {
    public static void main(String[] args) throws Exception {
        class ScannerLink implements AutoCloseable {
            public void close() throws IOException {
                throw new IOException("Close failed");
            }
        }
        try (var link = new ScannerLink()) {
            throw new IOException("Read failed");
        } catch (IOException failure) {
            System.out.println(failure.getMessage());
            System.out.println(failure.getSuppressed()[0].getMessage());
        }
    }
}
Output
Read failed
Close failed

This small test double always fails on close. Try-with-resources keeps the read error primary and attaches the close error as suppressed.

Finish a rehearsal import

A music teacher reads an attendance note using a scoped reader. The operator finishes reading inside a managed resource scope. What is the reader’s state after leaving the scope?

GivenRead “Attendance” → leave scope
Worked resultClosed

What to watch for

Closing releases the resource. Handle or propagate the IOException that opening, reading, or closing may report.

Documentation for Try-with-resources