What comes first – finally or catch block?

The key points are these:

  • In a try-(catch)-finally block, the finally for that particular try block is performed last
  • You can nest try blocks within another, and each of those nested try blocks can have their own finally, which would be performed last for those individual try blocks

So yes, finally is performed last, but only for the try block it’s attached to.

So given the following snippet:

try {
    try {
        throw null;
    } finally {
        System.out.println("Finally (inner)");
    }
} catch (Throwable e) {
    System.out.println("Catch (outer)");
}

This prints (as seen on ideone.com):

Finally (inner)
Catch (outer)

Observe that:

  • Within (inner), Finally is last (whether or not any catch was successful)
  • Catch (outer) follows Finally (inner), but that’s because Finally (inner) is nested inside another try block within (outer)

Similarly, the following snippet:

    try {
        try {
            throw null;
        } catch (Throwable e) {
            System.out.println("Catch (inner)");
        } finally {
            System.out.println("Finally (inner)");
            throw null;
        }
    } catch (Throwable e) {
        System.out.println("Catch (outer)");
    }

This prints (as seen on ideone.com):

Catch (inner)
Finally (inner)
Catch (outer)

References

Related questions

Leave a Comment