码迷,mamicode.com
首页 > 编程语言 > 详细

Java TryWtihResource语句

时间:2020-05-08 10:12:24      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:public   finally   stat   closeable   throws   语句   cep   exception   sed   

当需要关闭资源时,通常会使用try-finally语句

  public void test2() throws Exception {
    Resource resource = new Resource();
    try {
      System.out.println("doing somethings");
    } finally {
      resource.close();     
    }
  }

java7新增了tryWithResource语句专门用于处理资源关闭的情况,基本结构为:try()

public class TryWith {
  private class Resource implements AutoCloseable {

    @Override
    public void close() throws Exception {
      System.out.println("resource is closed");
    }
  }

  public void test() throws Exception {
    try(Resource resource = new Resource()) {
      System.out.println("doing something");
    }
  }

  public static void main(String[] args) throws Exception {
    TryWith tryWith = new TryWith();
    tryWith.test();
  }
}

括号内用于初始化资源,资源需要实现java.lang.AutoCloseable接口,即实现close()方法。 括号内可以初始化多个资源,比如try(Resource resource1 = new Resource();Resource resource2 = new Resource()){}

tryWithResource语句类似Python中的with..as语句

Java TryWtihResource语句

标签:public   finally   stat   closeable   throws   语句   cep   exception   sed   

原文地址:https://www.cnblogs.com/Peter2014/p/12848419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!