Is the close method in idiom try-with-resources not called if the constructor throws an exception?

I have a base class Baseand a child class Childthat extends it. Baseimplements java.lang.AutoCloseable.

Suppose the constructor for Childyields a Foo.

Now consider

try (Base c = new Child()){
    /*Some code*/
} catch (final Foo e){
    /*Some more code*/
}

Is the method called Base#closeif an exception is thrown? It is not on my machine, but is it something that standardized JLS?

+4
source share
2 answers

Yes, closeit will not be called. This is indicated in the JLS section 14.20.3 :

. ( ), , try-with-resources, . , try , try-with-resources .

, . , , ,. . , , try .

, . , close .

+9

close . , , , , :

try (Base b = makeBase()) {
    ...
}

makeBase

Base makeBase() {
    throw new RuntimeException();
}
+5

Source: https://habr.com/ru/post/1623426/


All Articles