【问题标题】:What happens when with try resource when opening the resource throws exception?当打开资源时尝试资源抛出异常时会发生什么?
【发布时间】:2016-10-26 18:44:56
【问题描述】:

我正在使用 try 表达式,并阅读了有关此的 java 文档。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

我知道,如果资源关闭和 try 块中的代码都抛出异常,那么关闭异常会被抑制。但是如果资源打开抛出异常会发生什么?我需要用封闭的抓钩来抓它吗?这表现如何?

try (Statement stmt = con.createStatement()) {
        // use stmt here
}

假设创建语句引发了错误,现在会发生什么?被压制了吗?我想区分这个异常和在成功创建语句并且块抛出异常时可能抛出的任何异常。

感谢您的帮助!

【问题讨论】:

    标签: java exception try-catch


    【解决方案1】:

    假设创建语句引发了错误,现在会发生什么?是吗 压制?

    不,它不会被抑制,它会按原样抛出,实际上您的代码根据 Java 规范§14.20.3.1 相当于:

    Throwable primaryExc = null;
    Statement stmt = null;
    try {
        stmt = con.createStatement();
        // use stmt here
    } catch (Throwable e) {
        primaryExc = e;
        throw e;
    } finally {
        if (stmt != null) {
            if (primaryExc != null) {
                try {
                    stmt.close();
                } catch (Throwable ex) {
                    primaryExc.addSuppressed(ex);
                }
            } else {
                stmt.close();
            }
        }
    }
    

    所以你可以看到createStatement() 是否抛出异常,如果没有显式捕获,调用代码将不得不将此异常作为正常异常处理。

    还请注意,就像上面的等效代码 sn-p 一样,如果 stmt.close() 在被 try-with-resources 语句自动调用时抛出异常,调用代码将不得不处理此异常,因为它不会也被压制了。

    try-with-resources 语句添加了抑制异常的功能,以便在try 块中已经引发异常时,能够获取在资源上调用close() 时引发的异常,例如示例:

    try (Statement stmt = con.createStatement()) {
        throw new RuntimeException("foo");
    } catch (Exception e) {
        // Here e is my RuntimeException, if stmt.close() failed
        // I can get the related exception from e.getSuppressed()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多