SyntaxStudy
Sign Up
Java Beginner 1 min read

try-with-resources

try-with-resources, introduced in Java 7, is a special form of the try statement that automatically closes resources when the block exits, whether normally or due to an exception. Any object that implements the AutoCloseable interface (which includes Closeable) can be used as a resource. The resource is declared in parentheses after the try keyword, and the compiler generates the equivalent of a finally block calling close() for you. Multiple resources can be declared in a single try-with-resources statement, separated by semicolons. They are closed in the reverse order of their declaration, which mirrors the typical pattern of wrapping one stream around another. If both the try block and the close() method throw exceptions, the close() exception is suppressed and attached to the primary exception, accessible via getSuppressed(). This is a significant improvement over manually written finally blocks, which would silently discard the original exception. try-with-resources leads to cleaner, safer, and more readable code compared to manual resource management. It eliminates entire categories of bugs (resource leaks) and reduces boilerplate. When writing code that opens files, database connections, network sockets, or any other closeable resource, always prefer try-with-resources over a manual finally block.
Example
import java.io.*;
import java.nio.file.*;

public class TryWithResourcesDemo {

    // Custom AutoCloseable
    static class ManagedConnection implements AutoCloseable {
        ManagedConnection(String url) {
            System.out.println("Opening connection to " + url);
        }
        public void query(String sql) {
            System.out.println("Executing: " + sql);
        }
        @Override
        public void close() {
            System.out.println("Connection closed");
        }
    }

    static void readFileDemo(String path) {
        // Single resource — automatically closed
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Could not read file: " + e.getMessage());
        }
    }

    static void multipleResources() {
        // Multiple resources, closed in reverse order
        try (ManagedConnection conn = new ManagedConnection("db://localhost");
             PrintWriter log = new PrintWriter(System.out)) {
            conn.query("SELECT * FROM users");
            log.println("Query completed");
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        // Both conn and log are closed here automatically
    }

    public static void main(String[] args) {
        multipleResources();
        readFileDemo("nonexistent.txt"); // demonstrates catch
    }
}