CKTIS / Java
try-with-resources — automatic resource closing
The try-with-resources statement automatically calls close() on AutoCloseable resources. It defines their usage lifetime and specifies how closing exceptions are handled.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
try (Resource r = expression) {
// use r
}In try (Resource r = ...), Resource denotes the declared resource type, which must be a subtype of AutoCloseable. The type AutoCloseable itself meets this requirement. The ... stands for an initializer expression. When leaving the block, including through return or an exception, Java calls close() on the non-null resource.
Separate resources with semicolons. Initialization proceeds left to right; closing proceeds in reverse order. If initialization fails, previously initialized resources are closed. One failing close() does not skip the remaining closing attempts.
A variable declared in the header is implicitly final. You can also use try (r) if the existing variable is assigned beforehand and is final or effectively final, meaning it is not reassigned.
If the block throws an exception, it becomes the primary exception. If close() throws a different exception object, addSuppressed() records it as a suppressed exception, accessible through getSuppressed(), only if suppression is enabled on the primary exception. If suppression is disabled, the distinct closing exception is not recorded. If close() throws the same exception object as the block, addSuppressed() rejects self-suppression by throwing IllegalArgumentException, even if suppression is disabled. The IllegalArgumentException can then propagate instead of the original exception. With no earlier exception, the first closing exception becomes the primary exception. Optional catch and finally clauses execute after closing attempts; catch can also handle initialization and closing failures.
Examples
public class Main {
static final class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
try (Resource a = new Resource("A");
Resource b = new Resource("B")) {
System.out.println("work");
}
}
}Result
work close B close A
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.