Sub topic 13
Automatic Cleanup with try-with-resources
In the last chapters you saw that a resource has to be closed when you finish with it. A resource is an object that holds something outside your program, such as an open file or a network connection. Closing resources by hand in a finally block works, but it takes a lot of code and is easy to get wrong.
Java has a shorter way to do it. The try-with-resources statement is a try block that opens a resource and closes it for you when the block ends. The resource just has to implement AutoCloseable.
The Basic Shape
You declare the resource inside parentheses right after the word try:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FirstLine {
static String firstLine(Path path) throws IOException {
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.readLine();
}
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("demo", ".txt");
Files.writeString(file, "Hello\nWorld\n");
System.out.println(firstLine(file));
Files.delete(file);
}
}This prints Hello. The code never calls reader.close(), but the reader still gets closed. Java closes it as soon as the try block exits, and that holds in every case:
- The block finishes normally.
- The block runs a
return, likefirstLinedoes. - The block throws an exception, such as an
IOExceptionfromreadLine().
What You No Longer Write
| Manual cleanup with finally | try-with-resources |
|---|---|
| Declare the variable outside `try` | Declare it inside `try ( ... )` |
| Check for `null` before closing | No check needed |
| Call `close()` yourself in `finally` | Java calls `close()` for you |
| Easy to forget a step | Hard to get wrong |
When Does close() Run?
The order matters if you also add a catch block. Java closes the resource before the catch block runs. The small program below shows this with a made-up resource that prints messages:
public class CloseOrder {
static class Door implements AutoCloseable {
Door() {
System.out.println("door opened");
}
@Override
public void close() {
System.out.println("door closed");
}
}
public static void main(String[] args) {
try (Door door = new Door()) {
System.out.println("working");
throw new IllegalStateException("oops");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
} finally {
System.out.println("finally runs last");
}
}
}Output:
door opened
working
door closed
caught: oops
finally runs lastExercises
Exercise
In the CloseOrder program, the try body throws an exception. Does "door closed" print before or after "caught: oops", and why?
Show answer
It prints before. try-with-resources closes the resource as soon as the try body exits, and only then does the catch block run.
Exercise
Rewrite this method with try-with-resources so the reader is always closed: static String read(Path p) throws IOException { BufferedReader r = Files.newBufferedReader(p); String line = r.readLine(); r.close(); return line; }
Show answer
static String read(Path p) throws IOException { try (BufferedReader r = Files.newBufferedReader(p)) { return r.readLine(); } } The original never closes r if readLine() throws. The new version closes r in every case.