Video in progress
In try-with-resources, in what order are several resources closed, and what happens if close() throws an exception?
Resources are closed in reverse order of opening: the last one first. If an exception was thrown inside the block and close() throws too, the main error propagates out, and the one from close() is attached to it via getSuppressed().
📖 Answer
try (var in = Files.newInputStream(src);
var out = Files.newOutputStream(dst)) {
in.transferTo(out);
}
// closing order: out first, then in
The reverse order makes sense: a resource opened later often depends on the earlier one.
This is what a suppressed exception looks like:
try {
copy();
} catch (IOException e) {
log.error("Nusxa olishda xato", e);
for (Throwable s : e.getSuppressed()) {
log.warn("close() paytida ham xato: {}", s.getMessage());
}
}
In a stack trace they show up as Suppressed:; if you see that word in the log, know that it is a secondary error.
With the old try-finally it was the opposite: an error from close() in the finally would completely replace the main error, and you would go looking for the wrong cause.
If opening one resource fails, the ones opened before it are still closed.
Sign up to mark studied questions and save your progress.