繁体   English   中英

如何仅使用try-catch-finally结构重写具有两个资源的try-with-resources?

[英]How to rewrite try-with-resources with two resources using only try-catch-finally construction?

如何重写以下代码

try (A a = new A(); B b = new B()) {
//useful work here
}
catch (Exception e) {
//other code
}

使用try-catch-finally结构?

如果我们仅创建一种资源,那么这里有一个不错的链接。

不幸的是,当我们创建多个资源时,我不理解如何对此进行概括。

我不明白的一件事是,我们如何识别a发生了a而b却没有发生,反之亦然。

没有通用规则,但是您必须确保尝试关闭所有打开的资源,即使无法识别会发生什么情况以及在哪个资源中也是如此。

 void test() throws Exception {
    A a = null;
    B b = null;

    Exception myException = null;
    try {
        a = new A();
        b = new B();
        //useful work here
    } catch (Exception e) {
        myException = e;
        throw e;
    } finally {
        Throwable tA = handleCloaseable(a);
        Throwable tB = handleCloaseable(b);

        boolean throwIt = false;
        if (myException == null && tA != null || tB != null) {
            myException = new Exception();
            throwIt = true;
        }

        if (tA != null) {
            myException.addSuppressed(tA);
        }
        if (tB != null) {
            myException.addSuppressed(tB);
        }

        if (throwIt) {
            throw myException;
        }
    }
}

Throwable handleCloaseable(AutoCloseable e){ // your resources must implements AutoCloseable or Closeable
    if (e != null) {
        try {
            e.close();
        } catch (Throwable t) {
            return t;
        }
    }
    return null;
}

如果尝试关闭资源时发生任何异常,请创建新的Exception如果不存在),并添加异常,当您尝试使用addSuppressed关闭addSuppressed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM