【问题标题】:Autocloseable class doesn't invoke default close method自动关闭类不调用默认关闭方法
【发布时间】:2016-01-26 07:57:40
【问题描述】:

我有这段代码:

public class Resource implements AutoCloseable{

    private String s = "I am resource.";
    private int NuberOfResource;

    public Resource(int NuberOfResource) {
        this.NuberOfResource = NuberOfResource;
        System.out.println(s + " My number is: " + NuberOfResource);
    }

    @Override
    public void close() throws Exception {
        System.out.println("Closing...");
    }

    public void print(){
        System.out.println("Hello");
    }

主类:

public class Main {

    public static void main(String[] args) {
        int a, b = 0;
        a = 5;

        try {
            Resource first = new Resurs(1);
            Resource second = new Resurs(2);
            System.out.println("I will cause exception");
            a /= b;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

我想知道为什么会得到这个输出:

I am resource. My number is 1.
I am resource. My number is 2.
I will cause exception.
java.lang.ArithmeticException: / by zero

代替:

I am resource. My number is 1.
I am resource. My number is 2.
Closing...
Closing...
I will cause exception.
java.lang.ArithmeticException: / by zero

【问题讨论】:

    标签: java exception autocloseable


    【解决方案1】:

    因为你没有使用try-with-resourcesAutoCloseable 仅被调用,而不是常规的 try/catch 语句。

    正确的模式是

    try(Resource first = new Resource(1); Resource second = new Resource(2)) {
       // .. whatever
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 2013-12-28
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2019-12-09
      相关资源
      最近更新 更多