Java – my autoclosable Can the close () implementation detect potential exceptions?

When implementing autocolosable to use the Java 7 try with resources statement, I want to know if there are exceptions in the try block For example:

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 knowing how the try with resources statement translates to bytecode, I think this is impossible But is there (reliable!) Tips through instrumentation / reflection / some unrecorded compiler functions, allow me to start from autoclosable Access the runtimeException above in close()?

Note: I am an API designer and I have no control over the resources of API users Therefore, the implementation must be completed on the autoclosable site

Solution

The normal way to do this is to call explicitly at the end of the try block For example:

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

    transaction.commitOnClose();
}

Then at the end, you either abort the transaction or commit it depending on whether you call commitonclose()

It's not automatic, but it's very simple to implement - and very easy to read

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>