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

  1. Implement close() method
  2. close() is called automatically
  3. Even if exception occurs in try block

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler