Java 7 try-with-resources explained

While it is widely accepted than checked exceptions on Java wasn’t the brightest idea, when Java 7 came out there were a couple of things added regarding them that supposedly were going to make our lives easier. Catching multiple exceptions at the same time is easy enough, and I definitely think it is a straight forward and direct improvement. The other bit added, try-with-resources, looked like a good idea to me too, but I didn’t really know much about it until very recently, when I had a more careful look at the existent documentation an tried to get my head over it. In order to do that, I quickly wrote a few classes to illustrate the different possible scenarios depending on the place where an exception can be thrown.

Let’s have a look at the simplest scenario, where no exceptions are thrown.

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As you see, now you can declare and initialize some resource when writing your try. In this case, I am creating a resource of a custom class MyResource (which we’ll see in a moment), doing something with it, anyGivenAction(), and closing it. Before we get into many details, let me tell you the first bit I didn’t like about this: it was easier to refer to the different elements of an exception code snippet before… you could say the try, the catch or the finally and everybody would know what you’re talking about. Now it is a little bit more complicated: whereas the catch and the finally remain unaltered, the try now has two different “locations”: the resource area and the body of the try, the classic try, let’s say… no big deal, really, but still, old way of naming comes a bit short. For example, the connotations of an exception being thrown on the resource initialization area or on the body of the try are quite different.

But it gets worse. Let’s have a closer look to the resource area of the try…

   ...
        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
   ...

The only requisite for a resource to be declared there, as described on official Oracle documentation:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Let’s have a look at MyResource class:

class MyResource implements AutoCloseable {

    private boolean throwOnInitResource;
    private boolean throwOnAction;
    private boolean throwOnCloseResource;

    MyResource(boolean throwOnInitResource, boolean throwOnAction, boolean throwOnCloseResource) throws InitResourceException {
        this.throwOnInitResource = throwOnInitResource;
        this.throwOnAction = throwOnAction;
        this.throwOnCloseResource = throwOnCloseResource;
        if (this.throwOnInitResource) throw new InitResourceException();
        System.out.println("Resource opening, no exception.");
    }

    public void anyGivenAction() throws ActionException {
        if (this.throwOnAction) throw new ActionException();
        System.out.println("Any given action happening, no exception.");
    }

    public void close() throws CloseResourceException {
        if (this.throwOnCloseResource) throw new CloseResourceException();
        System.out.println("Resource closing, no exception.");
    }
}

It implements AutoCloseable interface as it implements the close() method specified by it. The other methods on the class are the constructor and anyGivenAction(), a dummy example of specific business logic for the class. The three boolean flags received on the constructor will control if an exception is thrown on any of the three methods of the class: while constructing, while executing anyGivenAction() or while closing the resource respectively. Every exception thrown is named after the place where it is thrown. This will be useful later on.

So why did I say it gets worse?… well, the finally section is intended to be used to close any resource open after the code that can thrown an exception uses it. But in the new try-with-resource, closing the resources happen automatically if they were declared on the resource area. So the resource area contains an implicit finally now, apart from being used to declare and initialized the resources to be used on the body of the try. You can have, also, an explicit finally in which wrap up anything not explicitly declared or initialized on the resource area of the try. See?, it got worse.

Let’s revisit the simplest case, where no exception is thrown anywhere:

public class NoExceptionsThrown {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

As the class is initialized with three false flags, no exception will be thrown within any of the three methods of MyResource. Let’s see the output of this program when run:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally

The catch is not visited, obviously, and the explicit finally is happening in the end, as expected. MyResource object declared on the resource area gets initialized and closed automatically, and in between, anything on the body of the try will happen. In this case, anyGivenAction(). Expected behaviour so far, nothing strange.

If an exception is thrown now by the code inside the catch, it would make no difference, since that section wouldn’t be visited. What happens if an exception is thrown inside the explicit finally, though?

public class OnlyFinally {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output would be:

Resource opening, no exception.
Any given action happening, no exception.
Resource closing, no exception.
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.OnlyFinally.main(OnlyFinally.java:17)

Nothing unexpected here either. But let’s have a look at the different cases of an exception being thrown while inside MyResource, and see how they combine with exceptions being thrown on the catch and the explicit finally. It can get really funny, bear with me here…

The simplest case is when we get an exception while initializing MyResource:

public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(true, false, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

The first true argument when building MyResource will trigger the exception on construction. In that case the exception is caught in the catch:

Catching class trywithresources.exceptions.InitResourceException
At the finally

What happens if the exception is thrown within the body of the try, though?

public class OnlyAction {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, false)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

In this case an exception is thrown on anyGivenAction(), have a look at the second argument true on MyResource construction. The output would be:

Resource opening, no exception.
Resource closing, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Before we get into the catch code that will handle the exception, try-with-resource ensures that the resource is closed. The implicit finally code has executed before the catch, as expected, same as in Java 6.

What if an exception is thrown on the implicit finally, when closing the resource then?

public class ActionAndClosing {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

When run, the output would be:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally

Wait, what?! Didn’t you just say that we were going to throw an exception while closing the resource?, yes. Doesn’t that happen after we throw the exception on the body of the try, but before it gets treated on the catch?, yes. Isn’t it supposed to be treated on the catch, instead of the ActionException thrown on anyGivenAction() then?, well, you would think so… but no. The CloseResourceException thrown on the implicit finally gets suppressed. When confronted with more than one exception being thrown, the compiler is able to distinguish the important one, let’s say… the one that happened during the business logic being executed within the body of the try, instead of the one being thrown within the implicit finally of the try-with-resources, where you are just closing the resource. If you still want to know about the suppressed exceptions, you can get them from the one that was finally thrown:

public class ActionAndClosingSuppressedInfo {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception exceptionThrown) {
            System.out.println("Catching " + exceptionThrown.getClass());
            for (Throwable exceptionSuppressed: exceptionThrown.getSuppressed()) {
                System.out.println("Suppressed: " + exceptionSuppressed);
            }
        }
        finally {
            System.out.println("At the finally");
        }
    }
}

Output of this:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
Suppressed: trywithresources.exceptions.CloseResourceException
At the finally

It kind of makes sense than the exception officially being thrown is the one happening on the body of the try, instead of the one happening on the implicit finally. The problem is that this behaviour is completely opposed to the one we got if the exception is being thrown on the explicit finally area. As you may remember from Java 6 lost exception problem, when an exception is thrown in there, it doesn’t really matter if you had an exception or not being thrown in the body of the try, or even in the catch for what it’s worth, the only and final exception being thrown would be the one on the explicit finally. So, for example, in the scenario where you have an exception being thrown on anyGivenAction(), while closing the resource, even when catching the exception and on the explicit finally:

public class AllButOpening {

    public static void main(String[] args) throws Exception {

        try (MyResource resource = new MyResource(false, true, true)) {
            resource.anyGivenAction();
        }
        catch (Exception e) {
            System.out.println("Catching " + e.getClass());
            throw new CatchException();
        }
        finally {
            System.out.println("At the finally");
            throw new FinallyException();
        }
    }
}

Output is:

Resource opening, no exception.
Catching class trywithresources.exceptions.ActionException
At the finally
Exception in thread “main” trywithresources.exceptions.FinallyException
at trywithresources.AllButOpening.main(AllButOpening.java:19)

A behaviour which is consistent with the Java 6 exception treatment but it’s opposed to what Java 7 does on try-with-resources implicit finally.

I suppose that what they’ve tried to do with the suppressed exceptions is precisely fix Java 6 problem when you literally lose an exception if another is thrown on the explicit finally.

It seems to me a half-way solution for a problem that should never has been there anyway, quite incoherent with the previous version of the language to say the least.

I’m really sorry about the extension of the post, but certain level of detail was necessary to illustrate the different outcomes of the possible cases. I hope you found it useful.

Leave a Reply

Your email address will not be published. Required fields are marked *