Video in progress

Strong Middle ☕ Core Java

In try-with-resources, if both the try block and close() throw an exception, which one is lost?

Neither is lost. The main one is the one thrown out of the try block, and the one from close() is attached to it as suppressed; you get it with getSuppressed().

📖 Answer

The old try/finally had a problem: if close() threw an exception inside finally, it completely "covered up" the original error from the try. The log only showed "close failed", and the real cause was lost.

try-with-resources closes that gap:

try (var in = new FileInputStream(path)) {
    parse(in);                 // threw IOException("bad format")
}                              // close() also threw IOException("disk")
catch (IOException e) {
    log.error("asosiy: {}", e.getMessage());       // bad format
    for (Throwable s : e.getSuppressed()) {
        log.error("yopishda: {}", s.getMessage()); // disk
    }
}

Other things to know:

  • resources are closed in the reverse order of their declaration;
  • if the try block finishes normally and only close() fails, that error becomes the main one;
  • e.printStackTrace() and SLF4J/Logback also print suppressed exceptions (a Suppressed: line), so read the log to the end.

If you close things by hand with finally, you can do the same with addSuppressed(), but it's easier to just switch to try-with-resources.