Try-With-Resources for AutoCloseable

Demonstrates try-with-resources with custom AutoCloseable objects, ensuring proper resource cleanup even when exceptions occur during resource usage.

JavaConfig Management

Code

snippet
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");
    }
}