首页 > 其他 > 详细

1.3.4 try-with-resources (TWR)

时间:2016-01-05 15:08:57      阅读:162      评论:0      收藏:0      [点我收藏+]

其基本设想是把资源(比如文件或类似的东西)的作用域限定在代码块内,当程序离开这个代码块时,资源会被自动关闭;

要确保try-with-resources生效,正确的用法是为各个资源声明独立变量;

目前TWR特性依靠一个新定义的接口实现AutoCloseable;TWR的try从句中出现的资源类都必须实现这个接口;(并非所有的资源相关的类都采用了这项新技术;JDBC4.1已经具备了这个特性;)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class CoinTWR {

    @SuppressWarnings("null")
    public static void main(String[] args) throws IOException {// 抛出异常
        
        /** 资源管理 **/
        try (FileInputStream fin = new FileInputStream("someFile.bin");
                ObjectInputStream in = new ObjectInputStream(fin)) {
            // ...
        }
        
        /** 改善了错误跟踪的能力(注意其中被抑制的NullPointerException简称NPE)
         * Ran As Java Application:
         * Exception in thread "main" java.lang.NullPointerException
         *             at cointest.CoinTWR.main(CoinTWR.java:21)
         */
        try (InputStream i = null) {
            i.available();
        }

    }
    
}

 

1.3.4 try-with-resources (TWR)

原文:http://www.cnblogs.com/springup/p/5102125.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!