Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java try-with-resources Statement
Automatic Resource Management



Managing system resources like files, sockets, or database connections is a critical responsibility in programming. Forgetting to close them can lead to memory leaks or locked resources. That’s where Java’s try-with-resources steps in — an elegant construct that automates resource management and simplifies cleanup.

What is try-with-resources in Java?

The try-with-resources statement is a special form of the try statement that ensures each resource is closed automatically at the end of the statement. Introduced in Java 7, it eliminates the need for verbose finally code blocks to close resources.

Key Requirement

The resource must implement the java.lang.AutoCloseable interface (or java.io.Closeable for older IO classes). Most Java IO and JDBC classes already do.

Basic Syntax

try (ResourceType resource = new ResourceType()) {
    // use the resource
} catch (Exception e) {
    e.printStackTrace();
}

Classic Example Without try-with-resources

Before Java 7, developers had to close resources manually, typically in a finally block.

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("input.txt"));
    System.out.println(reader.readLine());
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null)
            reader.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

Same Example With try-with-resources

try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
    System.out.println(reader.readLine());
} catch (IOException e) {
    e.printStackTrace();
}
Hello from file!

Notice how there's no need to explicitly close the reader. It’s handled behind the scenes — reliably and cleanly.

Multiple Resources in try-with-resources

You can manage more than one resource by separating them with semicolons in the try block.

try (
    BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
    BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))
) {
    String line = reader.readLine();
    writer.write("Copied: " + line);
} catch (IOException e) {
    e.printStackTrace();
}

This structure ensures writer.close() and reader.close() are both called, in reverse order of their creation.

Custom Resource with AutoCloseable

You can create your own resource class by implementing AutoCloseable.

class MyResource implements AutoCloseable {
    public void doSomething() {
        System.out.println("Working with MyResource");
    }

    @Override
    public void close() {
        System.out.println("Closing MyResource");
    }
}

public class Test {
    public static void main(String[] args) {
        try (MyResource res = new MyResource()) {
            res.doSomething();
        }
    }
}
Working with MyResource
Closing MyResource

What Happens on Exceptions?

If an exception is thrown inside the try block, the resource is still closed before the catch or finally block is executed. You can even catch suppressed exceptions (thrown during close()) using Throwable.getSuppressed().

class FaultyResource implements AutoCloseable {
    public void use() {
        throw new RuntimeException("Something went wrong in use()");
    }

    @Override
    public void close() {
        throw new RuntimeException("Something went wrong in close()");
    }
}

public class SuppressedExample {
    public static void main(String[] args) {
        try (FaultyResource res = new FaultyResource()) {
            res.use();
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
            for (Throwable suppressed : e.getSuppressed()) {
                System.out.println("Suppressed: " + suppressed.getMessage());
            }
        }
    }
}
Caught: Something went wrong in use()
Suppressed: Something went wrong in close()

Advantages of try-with-resources

When Should You Use It?

Use try-with-resources when you are dealing with resources like:

Conclusion

The try-with-resources statement is more than just syntactic sugar — it enforces good habits and removes the human error from manual cleanup.

QUIZ

Question 4:Which of the following best describes the role of AutoCloseable in try-with-resources?

Question 5:Resources declared in a try-with-resources statement are closed in the same order they were created.

Question 6:Which of the following are advantages of using try-with-resources?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M