AutoCloseable
The interface of a resource that can be closed by try-with-resources.
Available since: Java 7
Syntax
public interface AutoCloseable {
void close() throws Exception;
}Examples
Resources are closed in reverse order:
record Resource(String name) implements AutoCloseable {
Resource {
IO.println("open " + name);
}
public void close() {
IO.println("close " + name);
}
}
void main() {
try (var a = new Resource("A"); var b = new Resource("B")) {
IO.println("working");
}
}Output:
open A
open B
working
close B
close ANotes
Implement it in your classes that hold a file, a connection or a lock. The interface declares close() with throws Exception, but your implementation may throw a narrower exception or none — then no catch is needed. Its subinterface Closeable from java.io uses throws IOException.
See also
- try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.
- IOException — A checked exception for input and output errors: files, network, data streams.
Related recipes
In the tutorial
- try-with-resources — Closing resources automatically in Java — try-with-resources, the AutoCloseable interface, several resources, closing order and suppressed exceptions.