Multiple Resources in Try-With-Resources
Fast recall
Quick revision
Core answer
Whether you know multiple resources are semicolon-separated and closed in reverse declaration order
Using commas instead of semicolons, or assuming close order matches declaration order
Explain why reverse order matters when one resource depends on another (e.g., ResultSet before Statement before Connection)
Interview-ready guide
Interview answer
Multiple resources are separated with semicolons. Their initializers run left to right and every successfully initialized resource closes in reverse order. If a later initializer fails, the earlier resources still close. Java also continues attempting the remaining closes after one close fails.
If the body already failed, close failures are suppressed under that body exception. If the body succeeded, the first close failure becomes primary and later close failures are suppressed under it. That distinction is important when reading a trace.
Multiple Resources in Try-With-Resources
Direct Answer
Yes. Separate resources with semicolons. Initializers run left to right, and every successfully initialized resource is closed in reverse order. If a later initializer fails, earlier resources are still closed. If the body succeeds but several closes fail, the first close failure is primary and later close failures are suppressed; if the body fails, close failures are suppressed under the body failure.
Code Example
Two resources separated by a semicolon — watch the output close B before A.
static class Res implements AutoCloseable {
final String name;
Res(String name) { this.name = name; System.out.println("open " + name); }
public void close() { System.out.println("close " + name); }
}
public static void main(String[] args) {
try (Res a = new Res("A");
Res b = new Res("B")) { // semicolons between resources
System.out.println("using A and B");
}
}
// Output:
// open A
// open B
// using A and B
// close B <- reverse order
// close A
Common Mistakes & Pitfalls
- Using commas instead of semicolons between resources — won't compile.
- Assuming declaration order = close order. It's the reverse.
- Manually closing in the wrong order in legacy code — leads to 'connection already closed' errors.
- Cramming unrelated resources into one header when separate try blocks would read clearer.
Check your understanding
Answer these without looking back at the article.
- What happens if close() throws an exception in try-with-resources?
- What are suppressed exceptions and how do you access them?
- Can a resource declared in try-with-resources be used outside the try block?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.