首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用两个资源仅使用try-catch-finally结构重写try- with -resources?

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

Stack Overflow用户
提问于 2017-12-25 08:23:32
回答 1查看 913关注 0票数 2

如何重写以下代码

代码语言:javascript
复制
try (A a = new A(); B b = new B()) {
//useful work here
}
catch (Exception e) {
//other code
}

使用try-catch-finally构造?

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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-25 08:44:24

没有一般规则,但您必须确保尝试关闭所有打开的资源,即使您不知道发生了什么以及在哪个资源中发生了什么。

代码语言:javascript
复制
 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关闭时添加异常

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47964866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档