Try-with-resources and return statements in java

2019-01-19 10:06发布

I'm wondering if putting a return statement inside a try-with-resources block prevents the resource to be automatically closed.

try(Connection conn = ...) {
    return conn.createStatement().execute("...");
}

If I write something like this will the Connection be closed? In the Oracle documentation it is stated that:

The try-with-resources statement ensures that each resource is closed at the end of the statement.

What happens if the end of the statement is never reached because of a return statement?

2条回答
叛逆
2楼-- · 2019-01-19 10:11

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.

查看更多
Juvenile、少年°
3楼-- · 2019-01-19 10:23

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");
    }
}
查看更多
登录 后发表回答