HuntExams Academy logo
JavaIntermediate#exceptions

Explain try-with-resources.

Answer

A try statement that declares resources implementing AutoCloseable; they are closed automatically at the end of the block, even on exception. Replaces verbose finally blocks.

Example

try (BufferedReader br = new BufferedReader(new FileReader("f.txt"))) {
  System.out.println(br.readLine());
} // br.close() called automatically

Detailed explanation

Try-with-resources, introduced in Java 7, is a try statement that automatically closes resources when execution leaves its block, whether normally, through a return, or because an exception occurs. A resource must implement AutoCloseable, whose close() method performs cleanup. Closeable, commonly used by I/O classes, extends AutoCloseable. This construct is useful for files, streams, JDBC connections, and other objects that hold external resources. Unlike garbage collection, it provides predictable cleanup at a defined point in program execution.

In the example try (BufferedReader br = new BufferedReader(new FileReader("f.txt"))) { System.out.println(br.readLine()); }, Java calls br.close() after the body finishes. Closing BufferedReader also closes its underlying reader, so a separate close call for FileReader is unnecessary once the wrapper is successfully created. Multiple resources can be declared inside the parentheses, separated by semicolons. They are initialised from left to right and closed in reverse order. If initialisation of a later resource fails, previously initialised resources are still closed; a resource whose value is null is skipped.

Under the hood, the compiler generates cleanup and exception-handling logic equivalent to carefully written try/finally code; it does not rely on the garbage collector. If both the body and close() throw exceptions, the body's exception remains the primary exception, while the closing exception is attached as a suppressed exception. You can inspect suppressed exceptions using Throwable.getSuppressed(). If only closing fails, that exception propagates normally. With multiple resources, Java still attempts the remaining closes after one close fails. An accompanying catch or finally executes after automatic resource closing.

Since Java 9, the resource list can also reference an existing final or effectively final variable, for example try (reader) { ... }. Interviewers usually expect more than the phrase 'automatic closing': explain the AutoCloseable requirement, reverse closing order, and suppressed exceptions. Also clarify that checked exceptions from resource initialisation, the body, or close() must still be caught or declared. Try-with-resources reduces repetitive cleanup code without removing normal exception-handling responsibilities.

Key points to remember

  • Available since Java 7 for resources implementing AutoCloseable.
  • Closes non-null resources on normal exit, return, or exception.
  • Initialises resources left to right and closes them in reverse order.
  • Preserves the body's exception and attaches closing failures as suppressed exceptions.
  • Java 9 allows existing final or effectively final variables in the resource list.

Common mistakes candidates make

  • Assuming garbage collection closes files or database connections promptly.
  • Saying a close() exception replaces an exception already thrown by the body.
  • Assuming resources close in declaration order or that checked exceptions no longer need handling.

Likely follow-up questions

What is the difference between AutoCloseable and Closeable?

AutoCloseable.close() can declare Exception, while Closeable.close() declares IOException. Closeable extends AutoCloseable and requires repeated closing to have no effect, whereas AutoCloseable does not require idempotence.

What happens if both the try block and close() throw exceptions?

The exception from the try block is propagated as the primary exception. The exception from close() is attached to it as a suppressed exception and can be retrieved using getSuppressed().

Can you use a custom class with try-with-resources?

Yes, implement AutoCloseable and provide a public close() method containing the cleanup logic. Declare or reference an instance in the resource list, and Java will invoke close() when that try statement exits.

Interview tip: Start with automatic cleanup, walk through the BufferedReader example, and finish with reverse closing order and suppressed exceptions.

Related Interview Questions

1
JavaIntermediate#fundamentals

What is autoboxing and unboxing?

Open
2
JavaIntermediate#collections

What is the difference between Comparable and Comparator?

Open
3
JavaAdvanced#jvm

What is reflection in Java?

Open