try-with-resources step by step
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)try-with-resources is a try statement that declares its resources in round brackets right after try. Java closes each one for you when the block ends, on every path, with no finally and no null checks.
The resource declaration in brackets
try-with-resources is a try statement that declares resources in brackets and closes them automatically at the end, even when an exception is thrown.
A resource declaration is a variable created inside the brackets after try: try (BufferedReader reader = Files.newBufferedReader(file)) { ... }. Java added this form in Java 7. When the block ends, Java calls reader.close() automatically, whether the block finished normally, returned or threw.
Example 1 · Read a file with try-with-resources
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class TryWithResourcesDemo { public static void main(String[] args) throws IOException { Path file = Files.createTempFile("attendance", ".txt"); Files.writeString(file, "Present: 52 of 60\nAbsent: 8\n");
try (BufferedReader reader = Files.newBufferedReader(file)) { System.out.println(reader.readLine()); System.out.println(reader.readLine()); } // reader.close() runs here System.out.println("Reader closed");
Files.delete(file); // works on Windows too: nothing is open System.out.println("File deleted"); }}Present: 52 of 60 Absent: 8 Reader closed File deleted
What this code does
try (BufferedReader reader = ...)opens the file and Java promises to callreader.close()when the block ends. Nofinallyis written.- Because the reader is closed when the block ends,
Files.deleteworks even on Windows, where an open file is locked.
The variable exists only inside the try block, so nobody can use it after it is closed. It is also implicitly final: you cannot assign a new value to it inside the block.
try-finally and the null check for you. The resource is closed only if it was opened successfully.AutoCloseable versus Closeable
Only objects that implement AutoCloseable can go in the brackets. AutoCloseable (in java.lang, Java 7) has one method, void close() throws Exception. Any other type gives the compile error "try-with-resources not applicable to variable type".
Example 2 · An AutoCloseable and a Closeable class
import java.io.Closeable;import java.io.IOException;
class GatePass implements AutoCloseable { @Override public void close() throws Exception { System.out.println(" gate pass returned"); }}
class LabLogin implements Closeable { @Override public void close() throws IOException { System.out.println(" lab login ended"); }}
public class TwoInterfacesDemo { public static void main(String[] args) { System.out.println("AutoCloseable:"); try (GatePass pass = new GatePass()) { System.out.println(" entering the fest"); } catch (Exception e) { // close() may throw any Exception System.out.println(" error: " + e.getMessage()); }
System.out.println("Closeable:"); try (LabLogin login = new LabLogin()) { System.out.println(" running the lab program"); } catch (IOException e) { // close() may throw only IOException System.out.println(" error: " + e.getMessage()); } }}AutoCloseable: entering the fest gate pass returned Closeable: running the lab program lab login ended
What this code does
GatePass.close()is declaredthrows Exception, so thetryneedscatch (Exception e)(ormainmust declare it).LabLoginimplementsCloseable, whoseclose()throws onlyIOException, so a narrowercatch (IOException e)is enough. In both cases the close line prints after the body.
Example 3 · Error: a class that is not AutoCloseable
class Ticket { void close() { System.out.println("ticket closed"); }}
public class NotCloseableDemo { public static void main(String[] args) { try (Ticket t = new Ticket()) { System.out.println("travelling"); } }}NotCloseableDemo.java:9: error: incompatible types: try-with-resources not applicable to variable type
try (Ticket t = new Ticket()) {
^
(Ticket cannot be converted to AutoCloseable)
1 errorWhat this code does
Tickethas aclose()method, but it does not implementAutoCloseable. Java checks the interface, not the method name.- The fix is
class Ticket implements AutoCloseablewithpublic void close().
AutoCloseable:close() throws Exception. Used byScanner,Stream, database connections.Closeable:close() throws IOException, safe to call twice. Used by readers, writers and streams injava.io.Closeableis a kind ofAutoCloseable, so both work in the brackets.
Closeable (in java.io) is the older interface for I/O classes. It extends AutoCloseable and narrows the method to void close() throws IOException. So every Closeable works in try-with-resources, and you need to catch only IOException. Its documentation also says that closing twice must do nothing.
Fix the error
Fix the try-with-resources error
Read the error, then pick the line that fixes it.
Round 1 of 2
Change the class line so a Printer can go in the try brackets.
Error
Receipt.java:6: error: incompatible types: try-with-resources not applicable to variable type
try (Printer p = new Printer()) {
^
(Printer cannot be converted to AutoCloseable)close runs before catch and finally
The order is fixed: the body runs, then the resource is closed, then a matching catch runs if something was thrown, then finally. By the time your catch block starts, the resource is already closed.
Example 4 · The order: body, close, catch, finally
class Counter implements AutoCloseable { private final String name;
Counter(String name) { this.name = name; System.out.println("1. open " + name); }
void serve(boolean fail) { System.out.println("2. body: serving at " + name); if (fail) { throw new IllegalStateException("printer jam at " + name); } }
@Override public void close() { System.out.println("3. close " + name); }}
public class CloseOrderDemo { static void visit(String name, boolean fail) { try (Counter c = new Counter(name)) { c.serve(fail); } catch (IllegalStateException e) { System.out.println("4. catch: " + e.getMessage()); } finally { System.out.println("5. finally"); } }
public static void main(String[] args) { System.out.println("Fee counter, no problem:"); visit("fee counter", false); System.out.println("Exam cell, printer jams:"); visit("exam cell", true); }}Fee counter, no problem: 1. open fee counter 2. body: serving at fee counter 3. close fee counter 5. finally Exam cell, printer jams: 1. open exam cell 2. body: serving at exam cell 3. close exam cell 4. catch: printer jam at exam cell 5. finally
What this code does
- With no error the steps are 1, 2, 3, 5. With the printer jam they are 1, 2, 3, 4, 5: the counter is closed before the
catchblock runs. close()here has nothrowsclause, so nocatch (Exception e)is needed. The Write your own AutoCloseable lesson explains why that is allowed.
This is why the resource variable is not visible in catch or finally. Anything you still need from it, such as a line number, save into a variable declared before the try.
Order of execution
What runs when?
The body throws an exception. Tap the steps in the order Java runs them.
catch after try-with-resources also catches exceptions from the open and from close(), not only from the body.Using an existing effectively final variable as the resource
From Java 9, the brackets may hold just a variable name: try (reader) { ... }. The variable must already exist and be effectively final, which means it is never assigned again after its first value.
Example 5 · Java 9: an existing variable in the brackets
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class ExistingVariableDemo { public static void main(String[] args) throws IOException { Path file = Files.createTempFile("timetable", ".txt"); Files.writeString(file, "Mon: DBMS\nTue: Java\n");
BufferedReader reader = Files.newBufferedReader(file); System.out.println("Opened before the try");
try (reader) { // Java 9: an existing variable System.out.println(reader.readLine()); System.out.println(reader.readLine()); } System.out.println("Closed by try-with-resources");
Files.delete(file); }}Opened before the try Mon: DBMS Tue: Java Closed by try-with-resources
What this code does
readeris created before thetryand never assigned again, so it is effectively final andtry (reader)is allowed.- Java closes
readerwhen the block ends, exactly as if it had been declared inside the brackets.
Example 6 · Error: the variable is assigned twice
import java.io.BufferedReader;import java.io.IOException;import java.io.StringReader;
public class NotFinalDemo { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new StringReader("Mon: DBMS")); reader = new BufferedReader(new StringReader("Tue: Java"));
try (reader) { System.out.println(reader.readLine()); } }}NotFinalDemo.java:10: error: variable reader used as a try-with-resources resource neither final nor effectively final
try (reader) {
^
1 errorWhat this code does
readergets a second value, so it is not effectively final, andtry (reader)is rejected.- The fix is to remove the second assignment, or declare the second reader in the brackets:
try (BufferedReader r2 = ...).
Java 9 did not change anything else: the variable is closed at the end of the block as before.
This helps when the resource is created earlier, for example in a few lines before the try or by another method. If the variable is assigned twice, javac rejects it.
Next step
Check your understanding
12 quick questions