【问题标题】:Are resources closed before or after the finally?资源是在 finally 之前还是之后关闭?
【发布时间】:2014-07-30 12:19:17
【问题描述】:

在 Java 7 的 try-with-resources 中,我不知道 finally 块和自动关闭发生的顺序。顺序是什么?

BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed
try(AdvancedResource a = new AdvancedResource(b)) {

}
finally {
    b.stop(); // will this happen before or after a.close()?
}

【问题讨论】:

    标签: java java-7 finally try-with-resources


    【解决方案1】:

    finally 块是最后被执行的:

    此外,所有资源都将被关闭(或试图关闭) 关闭)到执行 finally 块时,与 finally 关键字的意图。

    引自 JLS 13; 14.20.3.2. Extended try-with-resources:

    【讨论】:

      【解决方案2】:

      资源在 catch 或 finally 阻塞之前关闭。看到这个tutorial

      try-with-resources 语句可以像普通的 try 语句一样有 catch 和 finally 块。在 try-with-resources 语句中,任何 catch 或 finally 块都会在声明的资源关闭后运行。

      评估这是一个示例代码:

      class ClosableDummy implements Closeable {
          public void close() {
              System.out.println("closing");
          }
      }
      
      public class ClosableDemo {
          public static void main(String[] args) {
              try (ClosableDummy closableDummy = new ClosableDummy()) {
                  System.out.println("try exit");
                  throw new Exception();
              } catch (Exception ex) {
                  System.out.println("catch");
              } finally {
                  System.out.println("finally");
              }
      
      
          }
      }
      

      输出:

      try exit
      closing
      catch
      finally
      

      【讨论】:

      • 疯了。所以当需要资源来处理捕获时,Try-with-resources 并不能很好地替代 try-catch-finally。
      • 资源不需要在catch 块中处理。
      • catch 块可能需要资源来完成它的任务。
      • 这很糟糕。我想我可以在 SQL 连接上使用 try-with-resources 时在 finally 中调用 rollback()。这样下去,我不行。另请参阅stackoverflow.com/a/218495/593146
      猜你喜欢
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多