java – 我的AutoCloseable.close()实现能否检测到潜在的异常?
发布时间:2020-12-14 05:53:15 所属栏目:Java 来源:网络整理
导读:在实现AutoCloseable以使用 Java 7 try-with-resources语句时,我想知道try块中是否存在异常.例如.: class C implements AutoCloseable { @Override public void close() { if (exceptionOccurred) something(); else somethingElse(); }} 为了说明这一点:
在实现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()而中止事务或提交它. 它不是自动的,但实现起来非常简单 – 而且阅读起来非常简单. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |