Custom AutoCloseable in Java: Explanation & Practice
Create a resource that auto-closes
Problem summary
Create a Connection class that implements AutoCloseable and automatically closes in try-with-resources.
Starter code
class Connection implements AutoCloseable {
private String name;
public Connection(String name) {
this.name = name;
System.out.println(name + " opened");
}
public void execute() {
System.out.println(name + " executing");
}
@Override
public void close() {
// Print closing message
}
}
public class Main {
public static void main(String[] args) {
try (Connection conn = new Connection("DB")) {
conn.execute();
}
System.out.println("Done");
}
}Expected output and test cases
- Resource auto-closed
DB opened DB executing DB closed Done
Hints
- Implement close() method
- close() is called automatically
- Even if exception occurs in try block
Related Exception Handling exercises
- Practice Graceful Degradation in Java
- Practice Exception Chaining in Java
- Practice Suppressed Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler