Quick revision
The short answer
The rewrite is try (BufferedReader r = Files.newBufferedReader(Path.of(path))) { return r.readLine(); }. Try-with-resources closes every declared resource automatically, in reverse order of declaration, whether the body returns normally or throws, and if both the body and close() throw, the close exception is attached to the primary one as a suppressed exception instead of replacing it. Resources must implement AutoCloseable, Java 9 lets us use an effectively final variable declared earlier with try (r) { ... }, and when wrapping streams we should declare each resource separately, because a nested constructor that throws would leak the inner one.
What to remember
In this answer, we rewrote the reader code as try (BufferedReader r = Files.newBufferedReader(Path.of(path))) { return r.readLine(); }. We saw that try-with-resources closes resources automatically in reverse order of declaration even when the body throws, keeps the body's exception as primary and adds close failures as suppressed exceptions, works with any AutoCloseable, and since Java 9 accepts an effectively final variable declared earlier. We also saw that nested wrapper constructors can leak the inner stream, so each resource should be declared separately.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The rewrite is try (BufferedReader r = Files.newBufferedReader(Path.of(path))) { return r.readLine(); }. Try-with-resources closes every declared resource automatically, in reverse order of declaration, whether the body returns normally or throws, and if both the body and close() throw, the close exception is attached to the primary one as a suppressed exception instead of replacing it. Resources must implement AutoCloseable, Java 9 lets us use an effectively final variable declared earlier with try (r) { ... }, and when wrapping streams we should declare each resource separately, because a nested constructor that throws would leak the inner one.
Why this question is asked
Closing resources correctly is one of those things that looks trivial and is surprisingly easy to get wrong. The original code works on the happy path, but it hides exceptions and can leak a file handle in an edge case. Interviewers ask for this rewrite to see whether we know exactly what try-with-resources guarantees, including the parts people forget, such as suppressed exceptions and closing order. In this answer, we will look at what is wrong with the original, write the try-with-resources version, see the guarantees one at a time with small experiments, and finish with the wrapper-constructor leak and the Java 9 form.
1What Is Wrong With the Original
The original code opens a reader, reads a line in a try block, and closes the reader in finally. It closes the reader on success and on failure, which is the main thing. But it has two weaknesses.
Notice the first weakness: if both readLine() and close() throw, the exception from finally replaces the one from the try block, so we lose the real cause and debug the wrong problem. The second weakness is in the first line: if the BufferedReader constructor threw after the FileReader was opened, nothing would close the FileReader, because the try block has not started yet.
2The Try-With-Resources Version
Try-with-resources, added in Java 7, declares the resource in parentheses after try. The compiler generates the closing code for us. We can also use Files.newBufferedReader (Java 8) with Path.of (Java 11), which opens the file and wraps it in one call, uses UTF-8 by default, and throws a clear NoSuchFileException if the file is missing.
Notice there is no finally and no explicit close. The resource variable r is in scope only inside the block and is implicitly final, so it cannot be reassigned to something else before closing.
3Guarantee 1: Closed Automatically, in Reverse Order
Every resource declared in the parentheses is closed when the block exits, whether by finishing, by return, or by an exception. With several resources, they are closed in the reverse order of declaration, the same order we would use by hand, because later resources often depend on earlier ones.
- Open resource a
- Open resource bif this throws, a is still closed
- Run the body
- Close b, then aalways, in reverse order
- Did the body throw?YesRethrow it, with close failures as suppressedNoRethrow the first close failure, if any
5 steps in order. Play them, or step through them one at a time.
4Guarantee 2: Close Failures Become Suppressed Exceptions
If the body throws and then close() also throws, try-with-resources keeps the body's exception as the primary one and attaches the close exception to it with Throwable.addSuppressed. Nothing is lost, and the stack trace prints both.
Compare this with the original code, which lost the disk error. If only close() throws, that exception becomes the primary one, as we would expect.
5AutoCloseable and the Java 9 Form
Any class implementing java.lang.AutoCloseable can be used as a resource. Its single method is void close() throws Exception; java.io.Closeable is the older subinterface for I/O, whose close throws IOException. JDBC Connection, Statement and ResultSet, streams, readers, channels, ExecutorService since Java 19, and many library types implement it.
Before Java 9, the resource had to be declared inside the parentheses. Since Java 9 we can name an existing variable, as long as it is final or effectively final, meaning it is never reassigned. That is handy when the resource was created earlier or passed in.
6The Nested Wrapper Constructor Leak
One subtle leak remains if we nest constructors inside a single declaration, as in try (BufferedReader r = new BufferedReader(new FileReader(path))). Only r is a resource. If FileReader opens the file and then the BufferedReader constructor throws, there is no r to close, and the FileReader leaks. BufferedReader's constructor rarely throws, but wrappers that do work in their constructor, such as GZIPInputStream reading a header or ObjectInputStream reading a stream header, throw often.
When both are declared, closing the wrapper usually closes the inner stream too, and then the inner one is closed a second time. That is harmless because Closeable.close must be idempotent, so a second call has no effect.
7Follow-up questions
Does try-with-resources work with a catch and finally?
Yes. We can add catch and finally blocks; they run after the resources have been closed. So in a catch block, the resource is already closed, and the exception we catch may carry suppressed close failures.
What if a resource is null?
A null resource is allowed and simply not closed. That is convenient for optional resources, but the body must not use it without checking.
Why not just catch and ignore exceptions from close()?
Because a close failure can mean data was not written, for example a buffered writer failing to flush on close. Suppressed exceptions keep that information without hiding the primary failure.
8Conclusion
In this answer, we rewrote the reader code as try (BufferedReader r = Files.newBufferedReader(Path.of(path))) { return r.readLine(); }. We saw that try-with-resources closes resources automatically in reverse order of declaration even when the body throws, keeps the body's exception as primary and adds close failures as suppressed exceptions, works with any AutoCloseable, and since Java 9 accepts an effectively final variable declared earlier. We also saw that nested wrapper constructors can leak the inner stream, so each resource should be declared separately.
Open with
I would write it as try (BufferedReader r = Files.newBufferedReader(Path.of(path))) { return r.readLine(); }. Try-with-resources guarantees that every resource declared in the parentheses is closed when the block exits, whether it returns normally or throws, and with several resources they are closed in reverse order of declaration.
Then, if they want more
The important improvement over the original finally block is exception handling: in the original, if readLine throws and then close throws too, the close exception replaces the real one and the cause is lost.
With try-with-resources, the body's exception stays primary and the close exception is added to it as a suppressed exception, so getSuppressed shows it and the stack trace prints both. Resources must implement AutoCloseable, or Closeable for I/O. Since Java 9 I can also write try (r) with a variable declared earlier, as long as it is effectively final.
One more thing: if I nest constructors in one declaration, like a GZIPInputStream around a FileInputStream, and the outer constructor throws, the inner stream is never closed because it is not a declared resource. So I declare each resource separately; closing twice is fine because close is idempotent.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9, Java 11, Java 19, Java 7
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Rewrite this with try-with-resources and explain what it guarantees:": https://scrivio-interview-library.netlify.app/java/exceptions/7822708c24/