Video in progress
What is a suppressed exception in try-with-resources, and where can it get lost?
If an exception is thrown inside the try block and then close() throws one too, the main error is kept and the one from close() is attached to it with addSuppressed. You get it with getSuppressed().
📖 Answer
The old try/finally style had a problem: if close() inside finally failed, it overrode the original error. You would see "Stream closed" in the log, and the real cause, say a parse error, was lost completely.
try-with-resources fixes this:
try (var in = new GZIPInputStream(Files.newInputStream(p))) {
parse(in); // threw IllegalStateException
} // close() threw an IOException too
catch (Exception e) {
log.error("import xatosi", e); // main: IllegalStateException
for (Throwable s : e.getSuppressed()) { // the close() error is here
log.warn("yopishda ham xato", s);
}
}
This is where people often slip in interviews: if the try block finishes normally and only close() fails, that error comes out as a regular exception, not a suppressed one.
Where does it get lost? Usually we lose it ourselves:
catch (Exception e) { log.error(e.getMessage()); }: only the message, no stack trace and no suppressed;- wrapping the error in another exception without passing the
cause:throw new ImportException("xato").
If SLF4J/Logback writes the full exception, the suppressed ones show up inside the stack trace as "Suppressed:". That is why you should always pass the exception object itself to the log, not just the message.
Sign up to mark studied questions and save your progress.