try-with-resources, suppressed Exceptions, and a peek at Java 9

try-with-resources was introduced in Java 7, quite a while ago. Yet, when a colleague of mine asked me about a related feature, suppressed Exceptions, I was unable to give him a satisfactory answer. That caused me to dig into this topic a bit, and this article was born.

Before try-with-resources was introduced, making sure a resource was properly closed was quite hard. Here’s an example:

private void tryWithSingleResource() {
    Resource resource = null;
    try {
        resource = new Resource("1");
        resource.doSomething();
    } finally {
        if (resource != null) {
            resource.close();
        }
    }
}

Any of the following may fail:

  • creating the object
  • working on it
  • closing it

One of the problem is that we lose information: a try-catch-finally block can only throw a single exception. That exception will be the last uncaught exception that happens (see https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2). In our case, this means that if close() fails, we’ll lose any exception thrown by doSomething(), or we have to add one more try-catch around the call to close(), catch its exception, possibly log its failure: (?content lost?)