try-with-resources: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most try-with-resources bugs come from four habits: a close() that an exception can skip, a wrong guess about the close order, reading only the main exception, and helper classes that close too early or never. Each has a short, reliable fix.
Mistake 1: a close() that an exception can skip
A close() written as the last line of a method runs only on the happy path. Any exception, early return or break in between skips it, and the resource leaks.
Example 1 · Mistake: close() at the end of the method
class Tracked implements AutoCloseable { static int open = 0; private final String name;
Tracked(String name) { this.name = name; open++; }
String read() { if (name.contains("bad")) { throw new IllegalStateException("bad row in " + name); } return "ok " + name; }
@Override public void close() { open--; }}
public class SkippedCloseDemo { static String leaky(String name) { Tracked t = new Tracked(name); String line = t.read(); // may throw t.close(); return line; }
static String safe(String name) { try (Tracked t = new Tracked(name)) { return t.read(); } }
public static void main(String[] args) { String[] files = {"mon.csv", "tue-bad.csv", "wed.csv", "thu-bad.csv"};
for (String f : files) { try { leaky(f); } catch (IllegalStateException e) { // skip the bad file } } System.out.println("leaky: still open = " + Tracked.open);
Tracked.open = 0; for (String f : files) { try { safe(f); } catch (IllegalStateException e) { // skip the bad file } } System.out.println("safe: still open = " + Tracked.open); }}leaky: still open = 2 safe: still open = 0
What this code does
leakycloses only whenread()succeeds. The two bad files throw, so two resources stay open.safedeclares the resource in try-with-resources, so the count is back to 0 even though the same two files fail.
The program gives correct answers, so the leak shows only as "Too many open files" or a locked file much later.
The fix is always the same: declare the resource in try-with-resources. Do this per file inside a loop, so each file is closed before the next one opens.
Mistake 2: guessing the close order wrong
Close order follows two rules. In one pair of brackets, resources close from the last declared to the first. A nested try-with-resources closes its own resources when its own block ends, before the outer block goes on.
Example 2 · Tracing nested try-with-resources
class Loud implements AutoCloseable { private final String name;
Loud(String name) { this.name = name; System.out.println("open " + name); }
@Override public void close() { System.out.println("close " + name); }}
public class NestedOrderDemo { public static void main(String[] args) { try (Loud a = new Loud("A"); Loud b = new Loud("B")) { try (Loud c = new Loud("C")) { System.out.println("inner body"); throw new IllegalStateException("boom"); } finally { System.out.println("inner finally"); } } catch (IllegalStateException e) { System.out.println("outer catch: " + e.getMessage()); } finally { System.out.println("outer finally"); } }}open A open B open C inner body close C inner finally close B close A outer catch: boom outer finally
What this code does
- The inner block throws, so C closes first, then the inner
finallyruns. The exception then leaves the outer body. - The outer block closes B and A (right to left), and only then runs its
catchandfinally.
To trace a program, walk it line by line: when a block ends (normally or by an exception), close its resources right to left, then run its catch, then its finally. Only then move to the enclosing block.
Mistake 3: reading only the main exception
Printing e.getMessage() shows only the main error. A failure can carry more: a cause (getCause(), the reason it happened) and suppressed exceptions (getSuppressed(), failures while closing). Code that logs only the message hides both.
Example 3 · A full error report: message, cause, suppressed
import java.io.IOException;
class Drive implements AutoCloseable { private final String name; private final boolean closeFails;
Drive(String name, boolean closeFails) { this.name = name; this.closeFails = closeFails; }
@Override public void close() throws IOException { if (closeFails) { throw new IOException("close failed: " + name); } }}
public class FullReportDemo { static void importMarks() throws IOException { try (Drive a = new Drive("pendrive", true); Drive b = new Drive("network share", true)) { try { Integer.parseInt("8O"); // letter O, not zero } catch (NumberFormatException e) { throw new IOException("bad marks in row 4", e); } } }
public static void main(String[] args) { try { importMarks(); } catch (IOException e) { System.out.println("Short report: " + e.getMessage()); System.out.println("Full report:"); System.out.println(" error: " + e.getMessage()); System.out.println(" cause: " + e.getCause().getMessage()); for (Throwable s : e.getSuppressed()) { System.out.println(" suppressed: " + s.getMessage()); } } }}Short report: bad marks in row 4 Full report: error: bad marks in row 4 cause: For input string: "8O" suppressed: close failed: network share suppressed: close failed: pendrive
What this code does
- The short report says only "bad marks in row 4". The full report adds the cause (the
NumberFormatExceptionfor8O) and both close failures. - The network share was declared last, so it closed first and its failure is the first suppressed exception.
When you report an error, print the cause and the suppressed list too, or log the whole exception object. A stack trace prints them all as Caused by: and Suppressed: blocks.
Mistake 4: a helper that closes too early or never
A closeable helper is your own class that holds a resource inside it, such as a report writer that owns a BufferedWriter. It must implement AutoCloseable and close what it owns in its close().
Example 4 · A closeable helper that owns its writer
import java.io.BufferedWriter;import java.io.IOException;import java.io.StringWriter;
class ReportWriter implements AutoCloseable { private final StringWriter target; private final BufferedWriter out; private boolean closed = false;
ReportWriter(StringWriter target) { this.target = target; this.out = new BufferedWriter(target); // owned by this helper }
void line(String text) throws IOException { if (closed) { throw new IllegalStateException("report already closed"); } out.write(text); out.newLine(); }
@Override public void close() throws IOException { if (closed) { return; } closed = true; out.close(); // flushes, then closes target }}
public class ReportHelperDemo { public static void main(String[] args) throws IOException { StringWriter sheet = new StringWriter(); ReportWriter report = new ReportWriter(sheet); try (report) { report.line("CSE: 58 of 60 passed"); report.line("ECE: 51 of 55 passed"); report.close(); // closing twice is safe } System.out.print(sheet);
try { report.line("MECH: 40 of 48 passed"); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } }}CSE: 58 of 60 passed ECE: 51 of 55 passed Error: report already closed
What this code does
ReportWritercreates theBufferedWriteritself, so it owns it and closes it inclose(), which flushes the two lines intosheet.- The
closedflag makes the secondclose()harmless and turns a lateline(...)call into a clearIllegalStateException.
Otherwise the inner resource is never closed and its buffer is never flushed.
The opposite bug is closing too early: a helper that closes a resource it only borrowed, or returns one it already closed. Keep the rules from this module: whoever opens closes, close() is safe to call twice, and use after close throws a clear error.
Finish up
Mark complete & continue
Next: Path: naming a file in Java