try-with-resources
A resource is something that must be closed: a file, a socket, a database connection, a lock. Java 7 added a form of try that closes the resources it names, in the reverse order of their creation, whether the body finished or threw. This lesson writes a resource of its own, because then every open and close is visible in the output.
AutoCloseable and the block
A class that implements AutoCloseable promises one method, close(), which may declare an exception. The try header declares the resources and the body uses them; the compiler writes the finally that closes them:
public class Order {
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("open " + name);
}
void use() {
System.out.println("use " + name);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
try (Resource first = new Resource("first");
Resource second = new Resource("second")) {
first.use();
second.use();
}
System.out.println("after the block");
}
}
javac -Xlint:all Order.java
java Order
open first
open second
use first
use second
close second
close first
after the block
The order of close
The two resources open in the order they are written and close in the opposite order, which is the rule a stack follows: the second resource may depend on the first, so it must go first. The line after the block proves that the close calls happen before the next statement and not at the end of the program.
A resource declared in the header is in scope in the body and nowhere else, which is why a program that wants to use a file after the block copies what it needs out first. The variable is effectively final, so the body cannot reassign it to another resource by mistake.
A close that fails too
If the body throws and the close throws as well, the body's exception is the one the caller sees and the close's exception is attached to it as suppressed. The program below throws from both and prints the two:
public class Suppressed {
static class Failing implements AutoCloseable {
private final String name;
Failing(String name) {
this.name = name;
}
@Override
public void close() {
throw new IllegalStateException("close failed: " + name);
}
}
public static void main(String[] args) {
try (Failing resource = new Failing("r")) {
throw new IllegalArgumentException("body failed");
} catch (RuntimeException e) {
System.out.println("caught: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("suppressed: " + suppressed.getMessage());
}
}
}
}
javac -Xlint:all Suppressed.java
java Suppressed
Suppressed.java:16: warning: [try] auto-closeable resource resource is never referenced in body of corresponding try statement
try (Failing resource = new Failing("r")) {
^
1 warning
caught: body failed
suppressed: close failed: r
The warning is javac noticing that the body never touches the resource, which is usually a mistake; here it is the shortest way to write the case. The output is the whole point: the caller catches the body's exception and the close's failure is not lost, it is in getSuppressed, where a log or a trace prints it. Before Java 7 the close in a finally replaced the original exception, and the body's failure disappeared.
The old finally
The form before Java 7 is a resource, a try and a finally, and it is still correct for one resource. The program prints the same sequence both ways, so the two forms can be compared:
public class OldWay {
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("open " + name);
}
void use() {
System.out.println("use " + name);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
Resource resource = new Resource("old");
try {
resource.use();
} finally {
resource.close();
}
try (Resource a = new Resource("new"); Resource b = new Resource("new2")) {
a.use();
b.use();
}
}
}
javac -Xlint:all OldWay.java
java OldWay
open old
use old
close old
open new
open new2
use new
use new2
close new2
close new
The old form closes one resource in the right place and has no answer for two: the second close would need its own try inside the finally, and the suppressed exception would still be lost. That is the argument for the new form: the amount of code that can be got wrong is the reason a language adds syntax.
Resources in the JDK
The classes a program opens every day implement AutoCloseable, so they fit the same block: Scanner of lesson 104, Files.lines and the other streams of lesson 105, a FileInputStream, a java.sql.Connection. A ByteArrayOutputStream does not need closing, and a String never does.
Java 9 added a second form, try (resource) with an existing variable, for a resource that was created earlier. It closes the variable the same way, and the variable must be effectively final. The third form, a catch, is the same as in lesson 096: the block may have both, and the resources close before the catch runs.
Exercises
- Add a third resource to Order and predict the six lines of the output before you run it.
- Make the close of Suppressed print instead of throwing, and compare the output.
- Write a resource that fails to open, and show that the earlier resource still closes.
- Change OldWay to the Java 9 form with the variable declared before the try.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which method must a resource implement?
Answer
close, from AutoCloseable
The try block closes what it names, so the interface has to promise close.
-
In which order do two resources of one try block close?
Answer
The reverse of the order they were declared in
The second resource may depend on the first, so it must be closed first.
-
Where does the exception of a failing close go when the body also threw?
Answer
Into getSuppressed of the body exception
The body failure is the one the caller needs, and the close failure is attached to it.
-
What does this program print?
public class Q1 { static class R implements AutoCloseable { private final String name; R(String name) { this.name = name; System.out.println("open " + name); } void use() { System.out.println("use " + name); } public void close() { System.out.println("close " + name); } } public static void main(String[] args) { try (R r = new R("a")) { r.use(); } System.out.println("done"); } }Answer
open a / use a / close a / done
The resource closes at the end of the block, before the next statement.
-
Why is the try-with-resources form better than try and finally for two resources?
Answer
It closes both in the right order and keeps the first exception
The nested finally of the old form is the code that people get wrong.
-
Which class of the JDK needs no close?
Answer
String
A String holds no resource outside the heap, so there is nothing to release.
-
What must be true of a resource declared before the try in the Java 9 form?
Answer
It is effectively final
The block closes the variable it names, so the variable may not be reassigned.
-
What does this program print?
public class Q2 { static class R implements AutoCloseable { private final String n; R(String n) { this.n = n; System.out.print("open "); } void use() { System.out.print("use "); } public void close() { System.out.print("close "); } } public static void main(String[] args) { try (R a = new R("a"); R b = new R("b")) { a.use(); b.use(); } System.out.println("end"); } }Answer
open open use use close close end
Both open, both are used, and both close in reverse order before end.
-
What does this program print?
public class Q3 { static class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } public static void main(String[] args) { try (R r = new R()) { throw new IllegalArgumentException("body"); } catch (RuntimeException e) { System.out.println(e.getMessage()); System.out.println(e.getSuppressed().length); } } }Answer
body / 1
The body exception is caught and the close exception is suppressed under it.
-
What does the compiler write for a try-with-resources block?
Answer
A finally that closes every resource in reverse order
The syntax is sugar over the try and finally that a person used to write.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev