java8 try resource_java8:try-with-resources

java8:try-with-resources

在try( …)里声明的资源,会在try-catch代码块结束后自动关闭掉

public class Trys {

private static void testAutoClose() {

AutoCloseable globalObj1 = null;

AutoCloseable globalObj2 = null;

try (

AutoCloseable obj1 = new AutoClosedImpl("obj1");

AutoCloseable obj2 = new AutoClosedImpl("obj2");

) {

globalObj1 = obj1;

int i = 1 / 0;

globalObj2 = obj2;

System.out.println("finished");

} catch (Exception e) {

System.out.println("no finished");

e.printStackTrace();

} finally {

try {

System.out.println("before finally close");

if (globalObj1 != null) {

globalObj1.close();

}

if (globalObj2 != null) {

globalObj2.close();

}

System.out.println("after finally close");

} catch (Exception e) {

e.printStackTrace();

}

}

}

private static class AutoClosedImpl implements AutoCloseable {

private String name;

AutoClosedImpl(String name) {

this.name = name;

}

@Override

public void close() throws Exception {

System.out.println(name + " closing");

}

}

public static void main(String[] args) {

testAutoClose();

}

}

结果:

凡是实现了AutoCloseable接口的类,在try()里声明该类实例的时候,在try结束后,close方法都会被调用catch 块中,看不到 try-with-recourse 声明中的变量。try结束后自动调用的close方法,这个动作会早于catch代码块的执行,也早于finally里调用的方法。不管是否出现异常(int i=1/0会抛出异常),try()里的实例都会被调用close方法越晚声明的对象,会越早被close掉。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值