Ch. 7 · Java

Java Try-With-Resources and Cleanup

Java Try-With-Resources and Cleanup. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Try-with-resources closes AutoCloseable resources on normal and exceptional completion. It coordinates primary and cleanup failures.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: A reader is closed even when parsing throws. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Acquire owned resources

Declare AutoCloseable resources whose lifetime belongs to the operation.

Step 2: Use structured cleanup

Let try-with-resources close them on success and failure.

Step 3: Inspect secondary failures

Cleanup exceptions can be suppressed when another exception is primary.

Worked scenario

A reader is closed even when parsing throws.

try (var reader = java.nio.file.Files.newBufferedReader(path)) {
  System.out.println(reader.readLine());
}
java

Path is an existing input Path. With multiple resources, closure happens in reverse declaration order. If reading and closing both fail, inspect the primary exception’s suppressed exceptions rather than losing cleanup evidence.

Common mistake

Ignoring suppressed exceptions can miss a cleanup problem while investigating the primary failure.

Verify the behavior

Inject body and close failures with a small test resource and confirm closure order.

Interview exercise

Explain closure order.

Answer and reasoning

Resources close in reverse declaration order; inspect suppressed exceptions when close also fails.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc