Try-With-Resources for AutoCloseable
Demonstrates try-with-resources with custom AutoCloseable objects, ensuring proper resource cleanup even when exceptions occur during resource usage.
Code
import java.io.*;
public class TryWithResources {
static class DatabaseConnection implements AutoCloseable {
private final String name;
public DatabaseConnection(String name) {
this.name = name;
System.out.println("Opening connection: " + name);
}
public void query(String sql) {
System.out.println("Executing on " + name + ": " + sql);
}
@Override
public void close() {
System.out.println("Closing connection: " + name);
}
}
static class FileHandle implements AutoCloseable {
private final String path;
public FileHandle(String path) throws IOException {
this.path = path;
System.out.println("Opening file: " + path);
}
public void write(String data) {
System.out.println("Writing to " + path + ": " + data);
}
@Override
public void close() {
System.out.println("Closing file: " + path);
}
}
public static void main(String[] args) {
try (DatabaseConnection conn = new DatabaseConnection("primary");
FileHandle file = new FileHandle("output.log")) {
conn.query("SELECT * FROM users");
file.write("Query completed");
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println("Resources auto-closed in reverse order");
}
}What the code does
Everything happens inside the classes TryWithResources, DatabaseConnection and FileHandle and the functions DatabaseConnection, query, close and write.
No finally block here — resources declared in the try header close themselves in reverse order.
Applying it
Entry signature: public DatabaseConnection(String name)
The run emits 7 labeled sections — Opening connection:, Executing on, Closing connection:, Opening file:, Writing to, Closing file:, Resources auto-closed in reverse order — one per step.
The demo flow inside main is DatabaseConnection, query and write — run the file to see it end to end.
Statements that matter
conn.query("SELECT * FROM users");
file.write("Query completed");
this.name = name;
Interactive Tools for This Topic
FAQ
- What does Try-With-Resources for AutoCloseable print when run?
- Execute the whole file; each printed line is prefixed with a label like `Opening connection:`, `Executing on`, `Closing connection:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.