Try-with-resources and return statements in java

前端 未结 3 649
Happy的楠姐
Happy的楠姐 2020-12-03 09:56

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

try(Connec         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 10:15

    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");
        }
    }
    

提交回复
热议问题