java – 我的AutoCloseable.close()实现能否检测到潜在的异常?

在实现AutoCloseable以使用 Java 7 try-with-resources语句时,我想知道try块中是否存在异常.例如.:
class C implements AutoCloseable {
    @Override
    public void close() {
        if (exceptionOccurred)
            something();
        else
            somethingElse();
    }
}

为了说明这一点:

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
        ;
}

现在,从了解how the try-with-resources statement translates to bytecode,我想这是不可能的.但是有没有(可靠!)技巧通过instrumentation / reflection /一些未记录的编译器功能,允许我从AutoCloseable.close()中访问上面的RuntimeException?

注意:我是一名API设计师,我无法控制API使用者的资源尝试代码.因此,必须在AutoCloseable站点上完成实现

解决方法

执行此操作的常规方法是在try块的末尾显式调用.例如:
try (CustomTransaction transaction = ...) {
    // Do something which might throw an exception...

    transaction.commitOnClose();
}

然后在结束时,你要么根据是否调用commitOnClose()而中止事务或提交它.

它不是自动的,但实现起来非常简单 – 而且阅读起来非常简单.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...