java - 哪个 close() 先运行?

标签 java jdbc

如果我有多个资源,在 try catch 中,哪个先关闭?

public class TestRes {
  public static void main(String[] args) {
    TestRes tr = new TestRes();
    tr.test();
  }

  public void test() {
    try (MyResource1 r1 = new MyResource1(); MyResource2 r2 = new MyResource2(); ) {
       System.out.print("T ");
    } catch (IOException ioe) {
      System.out.print("IOE ");
    } finally {
      System.out.print("F ");
    }
  }

  class MyResource1 implements AutoCloseable {
    public void close() throws IOException {
      System.out.print("1 ");
    }
  }

  class MyResource2 implements Closeable {
    public void close() throws IOException {
      throw new IOException();
    }
  }
}

此示例输出:

T 1 IOE F 

如果我改变顺序,那么...

public class TestRes {
  public static void main(String[] args) {
    TestRes tr = new TestRes();
    tr.test();
  }

  public void test() {
    try (MyResource2 r2 = new MyResource2(); MyResource1 r1 = new MyResource1();) {
       System.out.print("T ");
    } catch (IOException ioe) {
      System.out.print("IOE ");
    } finally {
      System.out.print("F ");
    }
  }

  class MyResource1 implements AutoCloseable {
    public void close() throws IOException {
      System.out.print("1 ");
    }
  }

  class MyResource2 implements Closeable {
    public void close() throws IOException {
      throw new IOException();
    }
  }
}

我得到相同的输出 - 为什么?

最佳答案

您似乎认为 close() 方法的异常会阻止调用其他 close() 方法。这是错误的

Java 语言规范,部分 14.20.3. try-with-resources , 说:

Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.

这意味着 close() 方法打印 1 将始终执行,第一部分回答您的 “哪个 close() 先运行?” 问题。

关于java - 哪个 close() 先运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601516/

相关文章:

java - Java 库最佳实践中的抛出异常

java - 我们如何在java中传递String[] args

java - java中读取多个不同名称的文本文件

java - 如何检查 ResultSet 是否包含特定命名的字段?

mysql - Spring JDBC 模板无法执行 FROM 子句中包含嵌套查询的查询

java - 项目 > 1000 的 SQL in 子句

java - mssql-jdbc-6.3.4.jre8-preview.jar 没有 sqljdbc_auth.dll

java - Java中如何判断一个字段是否为char[]类型(char数组)?

java - JPA 获取重复的行(结果都具有相同的值)

java - 如何使这个线程安全