Sub topic 13
Automatic Cleanup with try-with-resources
In the last two chapters you saw that resources such as files must be closed, and that closing them by hand in a finally block takes a lot of careful code. You also met the AutoCloseable interface. An interface is a list of methods a class promises to have. A class that implements AutoCloseable promises to have a close() method.
This chapter puts those two ideas together. The try-with-resources statement is a form of try that closes a resource for you when the block ends. You write less code, and the resource still gets closed on every path out of the block.
What try-with-resources looks like
A resource is an object that holds something outside your program, such as an open file, a network connection, or a database connection. It must be closed when you are done with it.
In a try-with-resources statement, you create the resource inside round brackets 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);
}
}Running this prints:
helloLook at the parts of the try line:
| Part | Meaning |
|---|---|
| `try` | Starts the statement, as usual |
| `( ... )` | The **resource specification**: the place where you open resources |
| `BufferedReader reader` | A variable that holds the resource |
| `= Files.newBufferedReader(path)` | The code that opens the resource |
| `{ ... }` | The body, where you use the resource |
Notice what is missing. There is no finally block and no call to reader.close(). Java adds the closing step for you. When the body finishes, Java calls reader.close(). This happens whether the body returns a value, reaches its last line, or throws an exception.
In this example, return reader.readLine(); reads the line first. Java then closes the reader, and only after that does the method actually return.
Before and after
Here is roughly the manual version you would need without try-with-resources:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FirstLineManual {
static String firstLine(Path path) throws IOException {
BufferedReader reader = Files.newBufferedReader(path);
try {
return reader.readLine();
} finally {
reader.close();
}
}
}This looks almost as short, but it has a hidden problem. Suppose readLine() throws an exception and then close() throws one too. The exception from close() replaces the first one, so you lose the real cause of the failure. try-with-resources handles this case correctly. A later chapter shows exactly how.
The order things happen in
You can still add catch and finally blocks to a try-with-resources statement. Knowing the order in which the pieces run matters, so the next program prints a number at each step:
public class OrderDemo {
static class Door implements AutoCloseable {
Door() {
System.out.println("1. door opened");
}
@Override
public void close() {
System.out.println("3. door closed");
}
}
public static void main(String[] args) {
try (Door door = new Door()) {
System.out.println("2. using door");
throw new IllegalStateException("something broke");
} catch (IllegalStateException e) {
System.out.println("4. caught: " + e.getMessage());
} finally {
System.out.println("5. finally runs");
}
}
}Output:
1. door opened
2. using door
3. door closed
4. caught: something broke
5. finally runsThe key point is step 3. The resource is closed before your catch block runs. By the time you are handling the error, the door is already shut. That means you cannot use the resource inside catch or finally. The variable is also out of scope there, so the compiler would not let you.
Rules you need to know
Java has a few rules for try-with-resources. The compiler enforces most of them, so it will catch your mistakes.
The type must be AutoCloseable
Only objects whose class implements AutoCloseable, or its child interface Closeable, can go in the brackets. If you try to use a String, the code will not compile:
error: incompatible types: try-with-resources not applicable to variable typeThe variable is final
A variable declared in the brackets is automatically final, which means you cannot assign a new value to it. A line like reader = null; inside the body is a compile error. This rule makes sure Java closes the same object you opened.
The variable only exists inside the body
The variable's scope is the part of the code where you can use it. A resource's scope is the body of the try. After the closing }, the name reader no longer exists. This is useful, because nobody can accidentally use a closed resource later.
close() can throw, too
The close() method in AutoCloseable is declared as throws Exception. Closeable.close() is declared as throws IOException. The compiler treats a checked exception from close() like one from the body. You must catch it or declare it with throws. That is why firstLine above declares throws IOException: both readLine() and close() can throw it.
If your own class's close() does not declare any exception, as Door does not, you have nothing extra to handle.
Edge cases
Some situations surprise beginners. Here is how each one behaves.
| Situation | What happens |
|---|---|
| The body finishes normally | `close()` runs, then `finally` |
| The body uses `return` | The return value is computed, `close()` runs, then the method returns |
| The body throws an exception | `close()` runs, then a matching `catch`, then `finally` |
| Opening the resource throws (for example, the file does not exist) | `close()` is **not** called, because there is no object to close. Control goes to `catch` |
| The resource expression gives `null` | Java skips `close()` instead of throwing a `NullPointerException` |
| `close()` throws but the body did not | The exception from `close()` is thrown, like any other exception |
Here is the "opening fails" case in code:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class MissingFile {
public static void main(String[] args) {
Path path = Path.of("does-not-exist.txt");
try (BufferedReader reader = Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Could not read: " + e);
}
}
}It prints something like:
Could not read: java.nio.file.NoSuchFileException: does-not-exist.txtNo reader was ever created, so there was nothing to close. Java knows this and does not call close().
Writing a resource of your own
Any class you write can work with try-with-resources. It only has to implement AutoCloseable. Here is a small timer that reports how long a block took:
public class TimerDemo {
static class Timer implements AutoCloseable {
private final String label;
private final long start = System.nanoTime();
Timer(String label) {
this.label = label;
}
@Override
public void close() {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(label + " took " + ms + " ms");
}
}
public static void main(String[] args) throws InterruptedException {
try (Timer t = new Timer("sleep")) {
Thread.sleep(100);
}
}
}It prints something like sleep took 100 ms. The report appears even if the body throws an exception. This shows that try-with-resources is more than a tool for files. You can use it for any "do this when I am finished" job.
Exercise
In OrderDemo, the body throws an IllegalStateException. Which runs first, the door's close() method or the catch block, and why does that order matter?
Show answer
close() runs first, before the catch block. That means the resource is already closed while you handle the error, so you cannot use it in catch or finally. The variable is also out of scope there.
Exercise
This code does not compile: try (BufferedReader r = Files.newBufferedReader(p)) { r = null; }. Why?
Show answer
A variable declared in the resource specification is implicitly final, so you cannot assign a new value to it. This guarantees that Java closes the same object that was opened.
Exercise
Files.newBufferedReader throws NoSuchFileException because the file is missing. Is close() called on the reader? Explain.
Show answer
No. The exception happened while the resource was being created, so no reader object exists. Java only calls close() on resources that were opened, and control goes straight to a matching catch block (or out of the method).