Lukas Eder Lukas Eder - 1 year ago 74
Java Question

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

When implementing an

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 {
public void close() {
if (exceptionOccurred)

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()"

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
from within

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

Answer Source

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...


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download