如何使用try-catch-finally构造用两个资源重写try-with-resources?

时间:2017-12-25 00:23:32

标签: java exception try-catch try-with-resources

如何重写以下代码

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

使用try-catch-finally构造?

如果我们只创建一个资源,则会有一个很好的链接here

不幸的是,在创建多个资源时,我不明白如何概括这一点。

我不明白的一件事是我们如何认识到a发生的事情并没有发生在' b'反之亦然。

1 个答案:

答案 0 :(得分:3)

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

 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

关闭时出现的异常