18

我正在阅读有关 JDK7 中的 try-with-resource 的信息,当我考虑升级我的应用程序以使用 JDK7 运行时,我遇到了这个问题。

例如,当使用 BufferedReader 时,write 抛出 IOException 并且 close 抛出 IOException .. 在 catch 块中,我担心 write 抛出的 IOException .. 但我不太关心 close 抛出的那个 ..

数据库连接也有同样的问题..和任何其他资源..

例如,我创建了一个可自动关闭的资源:

public class AutoCloseableExample implements AutoCloseable {

    public AutoCloseableExample() throws IOException{
        throw new IOException();
    }

    @Override
    public void close() throws IOException {
        throw new IOException("An Exception During Close");
    }

}

现在使用它时:

public class AutoCloseTest {

    public static void main(String[] args) throws Exception {
        try (AutoCloseableExample example = new AutoCloseableExample()) {
            System.out.println(example);

            throw new IOException("An Exception During Read");
        } catch (Exception x) {
            System.out.println(x.getMessage());
        } 
    }

}

如何在不必为诸如 BufferedReader 之类的类创建包装器的情况下区分此类异常?

大多数情况下,我将资源关闭在 finally 块内的 try/catch 中,而不关心如何处理它。

4

2 回答 2

15

让我们考虑一下这个类:

public class Resource implements AutoCloseable {

    public Resource() throws Exception {
        throw new Exception("Exception from constructor");
    }

    public void doSomething() throws Exception {
        throw new Exception("Exception from method");
    }

    @Override
    public void close() throws Exception {
        throw new Exception("Exception from closeable");
    }
}

和 try-with-resource 块:

    try(Resource r = new Resource()) {
        r.doSomething();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

1.全部 3 个 throw 语句启用。

将打印消息“来自构造函数的异常”,并且构造函数抛出的异常将被抑制,这意味着您无法捕获它。

2.构造函数中的 throw 被移除。

现在堆栈跟踪将在下面打印“方法中的异常”和“已抑制:可关闭的异常”。在这里你也无法捕捉到 close 方法抛出的抑制异常,但是你会知道被抑制的异常。

3.构造函数和方法的抛出被移除。

正如您可能已经猜到的那样,将打印“可关闭的异常”。

重要提示:在上述所有情况下,您实际上都在捕获所有异常,无论它们是在哪里引发的。因此,如果您使用 try-with-resource 块,则不需要用另一个 try-catch 包装该块,额外的块根本没用。

希望能帮助到你 :)

于 2013-12-18T15:14:20.817 回答
0

我建议使用如下示例中的标志:

static String getData() throws IOException {
    boolean isTryCompleted = false;
    String theData = null;
    try (MyResource br = new MyResource();) {

        theData = br.getData();
        isTryCompleted = true;

    } catch(IOException e) {
        if (!isTryCompleted )
            throw e;
        // else it's a close exception and it can be ignored
    }

    return theData;
}

来源:使用 try-with-resources 悄悄关闭资源

于 2018-01-02T00:18:53.953 回答