简体   繁体   English

try-with-resources 什么时候关闭资源?

[英]When does try-with-resources close the resource?

I'm preparing myself for fall exam in Object Oriented Programming and one type of tasks we are given is providing output from code which usually consists of some Exception handling problems.我正在为面向对象编程的秋季考试做准备,我们得到的一种任务是提供代码的输出,这些输出通常包含一些异常处理问题。

Now my question is when does try-with-resources close it's resource because my output is strictly dependent on output from class that implements AutoCloseable.现在我的问题是 try-with-resources 什么时候关闭它的资源,因为我的输出严格依赖于实现 AutoCloseable 的类的输出。

In provided code, what I don't understand why "close 1" output comes before "close 40", or why is object A(40) closed at the end of this block.在提供的代码中,我不明白为什么“close 1”输出在“close 40”之前出现,或者为什么对象 A(40) 在此块的末尾关闭。 Is it because A(50) is same type as A(40)?是因为 A(50) 与 A(40) 是同一类型吗?

My main question when does the AutoCloseable close the given resource, like in example m1 when i=1:我的主要问题是 AutoCloseable 何时关闭给定资源,例如当 i=1 时的示例 m1:

1) A(1) is created 1b) Try block is executed 2) A(1) is closed 3) ArrayIndexOutOfBoundsException is handled? 1) A(1) 被创建 1b) Try 块被执行 2) A(1) 被关闭 3) ArrayIndexOutOfBoundsException 被处理了吗?

public class Main {
    public static void main(String[] args) {
          int[] arr = new int[] { 15, 10 };
          for(int i=1; i>=-1; i--){
              try(A a40 = new A(40)) {
                  m1(arr, i);
                  A a50 = new A(50);
              }
              catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("array exc");
              }
              catch(Exception e) {
                System.out.println("main exc");
                break;
              }
              finally {
                System.out.println("main finally");
              }
          }
          System.out.println("main done");
        }

        private static void m1(int[] arr, int i) throws Exception {
          try(A a1 = new A(i)) {
            m2(arr[i] + arr[i+1], i);
          }
          catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("m1 exc");
          }
          System.out.println("m1 done");
        }

        private static int m2(int x, int y)  {
           int r = 0;
           try{
               A a2 = new A(x+y);
               r = x / y;
           }
           finally {
            System.out.println("m2 finally");
           }
           System.out.println("m2 done");
           return r;
        }
}

And class A which implements AutoCloseable:和实现 AutoCloseable 的 A 类:

public class A implements AutoCloseable {
      private int x;
      public A(int x){
        this.x = x;
           System.out.println("A " + x);
      }
      @Override
      public void close() throws Exception {
        System.out.println("close " + x);
      }
}

Here is output of provided code:这是提供的代码的输出:

A 40
A 1
close 1
m1 exc
m1 done
A 50
close 40
main finally
A 40
A 0
A 25
m2 finally
close 0
close 40
main exc
main finally
main done

The specification is pretty clear on this.规范对此非常清楚。

14.20.3. 14.20.3. try-with-resources 尝试资源

A try-with-resources statement is parameterized with local variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block . try-with-resources 语句使用局部变量(称为资源)进行参数化,这些变量在 try 块执行之前初始化并在执行 try 块之后按照与它们初始化的相反顺序自动关闭。

Your example is a bit convoluted.你的例子有点复杂。 Try to simplify it.尝试简化它。 There are two scenarios you are interested in: an exception thrown in the try block, an exception isn't thrown in the try block.您对两种情况感兴趣:在 try 块中抛出异常,在 try 块中未抛出异常。 You debugging messages is informative, so you will be able to track the flow easily.您调试的消息是信息丰富的,因此您将能够轻松跟踪流程。

You may want to look into decompiled .classes to see what actually was generated.您可能需要查看反编译的 .classes 以查看实际生成的内容。

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

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