您的位置:首页 > 其它

try-with-resources语句

2015-09-15 11:13 253 查看
传统的try catch finally 使用场景有 io流关闭,数据库连接池关闭等。

Java SE7新特性出来个try-with-resources,可以省略finally方法。

先直接上代码吧

TestTryWithResouce.java

@Slf4j
public class TestTryWithResouce {
@Test
public void test() {
try (Pool pool = new Pool()) {
pool.get();
Integer.parseInt("ddd");
} catch (Exception e) {
log.error(e.getLocalizedMessage());
}
}
}


Pool .java

@Slf4j
public class Pool implements AutoCloseable {
public void close() {
log.info("pool回收");
}

public Object get() {
log.info("得到对象");
return null;
}
}


输出结果:

2015-09-15 11:01:47,211 INFO [main] (Pool.java:12) - 得到对象

2015-09-15 11:01:47,240 INFO [main] (Pool.java:8) - pool回收

2015-09-15 11:01:47,240 ERROR [main] (TestTryWithResouce.java:15) - For input string: “ddd”

使用try with resources 等于将以前的finally里面的方法 放到try()里面去了,try里面多了一个(),pool类实现了AutoCloseable ,实现了接口里面colse()方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: