Search code examples
javatry-with-resourcesautocloseable

Can my AutoCloseable.close() implementation detect a potential exception?


When implementing an AutoCloseable to work with the Java 7 try-with-resources statement, I would like to know if there had been an exception within the try block. E.g.:

class C implements AutoCloseable {
    @Override
    public void close() {
        if (exceptionOccurred)
            something();
        else
            somethingElse();
    }
}

To illustrate this:

try (C c = new C()) {

    // This should cause a call to "something()"
    if (something)
        throw new RuntimeException();

    // This should cause a call to "somethingElse()"
    else
        ;
}

Now, from understanding how the try-with-resources statement translates to bytecode, I guess that's not possible. But is there any (reliable!) trick through instrumentation / reflection / some undocumented compiler feature that allows me to access the above RuntimeException from within AutoCloseable.close() ?

Note: I'm an API designer, and I cannot control API consumers' try-with-resources code. The implementation must thus be done at the AutoCloseable site


Solution

  • The normal way to do this is just to explicitly make a call at the end of the try block. For example:

    try (CustomTransaction transaction = ...) {
        // Do something which might throw an exception...
    
        transaction.commitOnClose();
    }
    

    Then in close, you'd either abort the transaction or commit it, based on whether commitOnClose() had been called or not.

    It's not automatic, but it's pretty simple to achieve - and very simple to read.