java - Autocloseable 类不调用默认关闭方法

标签 java exception autocloseable

我有这段代码:

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

最佳答案

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

正确的模式是

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

关于java - Autocloseable 类不调用默认关闭方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009153/

相关文章:

java - 自动关闭并抛出异常

java - 在 try-with-resources 中关闭动态数量的 AutoCloseable 对象

c# - 我的应用程序可以在我的 PC (Windows 7) 上运行,但不能在另一台 (XP) 上运行,我不确定如何继续诊断问题

visual-studio - 当我在代码编辑器中选择文本时 Visual Studio 崩溃

java - 无法弄清楚正则表达式问题

java - 自动关闭作为参数传递的资源

java - 使得元素之和小于或等于 k ​​的方式总数

java - @Async API 端点 Spring Webflux

java - 将 Java 字符串拆分为具有特殊字符和复杂情况的空格

java - 使用Java打开外部程序