简体   繁体   English

Java中的try-with-resources语句

[英]try-with-resources statement in Java

In this Java program example: 在这个Java程序示例中:

package test;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;

public class Test
{
    private static void example(){
        String url = "jdbc:oracle:thin:@//localhost:7856/xe";
        String user = "user";
        String password = "pass";
        try(Connection con = DriverManager.getConnection(url, user, password);
            Statement stmt = con.createStatement()){
            throw new OutOfMemoryError("Error");
        }catch (SQLException e){
            System.err.println("SQLException");
        }
    }

    public static void main(String [] args){
        try{
            example();
        }catch (OutOfMemoryError e){
            System.err.println("OutOfMemoryError");
        }
        // Rest of code here...
    }
}

When, in the body of the static method example(), the OutOfMemoryError error is thrown, Are Connection "con" and Statement "stmt" automatically closed before terminating the static method example() despite there is not any "catch" that catches these error so in the rest of code in main() is sure that these two objects are closed ? 当在静态方法example()的主体中抛出OutOfMemoryError错误时,在终止静态方法example()之前,Connection“con”和Statement“stmt”会自动关闭,尽管没有任何捕获这些的“catch”错误,所以在main()的其余代码中确保这两个对象是关闭的?

Thanks. 谢谢。

Yes; 是; the try-with-resources construct always closes the resource, even if it's an unchecked throwable (like OutOfMemoryError). try-with-resources构造总是关闭资源,即使它是一个未经检查的throwable(如OutOfMemoryError)。

This is specified in JLS 14.20.3 , which starts with a pretty generic statement that the resources are "closed automatically," but then goes into various examples of times when a resource is closed. 这在JLS 14.20.3中指定,它以一个非常通用的语句开始,即资源“自动关闭”,但随后会进入资源关闭时的各种示例。 Basically, any non- null resource is always closed, as if the close had been in the finally clause of a try-finally created just for that one resource. 基本上,任何非null资源总是关闭的,就好像close已经在为一个资源创建的try-finallyfinally子句中。 This is the case even if there are multiple resources in the try , as in your case ("An exception from the closing of one resource does not prevent the closing of other resources"). 即使在try有多个资源,也就是这种情况(例如,“关闭一个资源时的异常不会阻止关闭其他资源”)。

Simple class to demonstrate it: 简单的类来演示它:

public class Twr {
  private static class TwrCloseable implements AutoCloseable {
    private final String id;

    TwrCloseable(String id) {
      this.id = id;
    }

    @Override
    public void close() {
      System.out.println("closing " + id);
    }
  }

  public static void main(String[] args) {
    try (TwrCloseable closeable1 = new TwrCloseable("first");
         TwrCloseable closeable2 = new TwrCloseable("second")) {
      throw new OutOfMemoryError();
    }
  }
}

Output: 输出:

closing second
closing first
Exception in thread "main" java.lang.OutOfMemoryError
    at Twr.main(Twr.java:19)

Note that they're closed in reverse order; 请注意,它们以相反的顺序关闭; "second" is closed before "first." “第二个”在“第一个”之前关闭。 In your example, this means that the Statement is closed before the Connection , which is exactly what you want. 在您的示例中,这意味着StatementConnection之前关闭,这正是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM