try-with-resources语句
来源:互联网 发布:python pillow 安装 编辑:程序博客网 时间:2024/06/07 01:56
传统的try catch finally 使用场景有 io流关闭,数据库连接池关闭等。
Java SE7新特性出来个try-with-resources,可以省略finally方法。
先直接上代码吧
TestTryWithResouce.java
@Slf4jpublic 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
@Slf4jpublic 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()方法
0 0
- try-with-resources 语句
- try-with-resources语句
- try-with-resources语句
- java try-with-resources 语句
- java7新特性:Try - with - Resources语句
- try-with-resources 语句,自动资源释放
- 理解try-with-resources语句及示例
- Java7之try-with-resources语句
- Java 7中的try-with-resources语句
- Java7 新特性:try() 语句 即 try-with-resources
- try-with-resources
- Try-with-resources (TWR)
- try-with-resources 简介
- try-with-resources详解
- java7 [try-with-resources]
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- Java SE7新特性之try-with-resources语句
- webrtc音频录制流程(含编码流程)
- android开源框架andorid-async-http使用(下载上传文件)
- Ant+Junit产生java的单元测试报告
- Class文件内容及常量池
- 【转】常用的.net开源项目
- try-with-resources语句
- POJ3185 The Water Bowls【高斯消元法】
- iOS runtime方法详解之添加类
- Python+OpenCV学习(13)---meanshift目标跟踪
- libevent 编程 一
- Java动态绑定机制的内幕
- Yii Framework的获取与项目的新建
- VS2008调试Release程序--Dump文件方式
- 带有分割线的GridView九宫格的完美实现