1

私はこのコードを持っています:

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
4

1 に答える 1

10

を使用していないためですtry-with-resources。通常のステートメントAutoCloseableではなく、それでのみ呼び出されます。try/catch

正しいパターンは

try(Resource first = new Resource(1); Resource second = new Resource(2)) {
   // .. whatever
}
于 2016-01-26T07:59:47.930 に答える