Try-with-resources and return statements in java

混江龙づ霸主 提交于 2019-11-28 10:40:15

Based on Oracle's tutorial, "[the resource] will be closed regardless of whether the try statement completes normally or abruptly". It defines abruptly as from an exception.

Returning inside the try is an example of abrupt completion, as defined by JLS 14.1.

The resource will be closed automatically (even with a return statement) since it implements the AutoCloseable interface. Here is an example which outputs "closed successfully":

public class Main {

    public static void main(String[] args) {
        try (Foobar foobar = new Foobar()) {
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Foobar implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("closed successfully");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!