使用try catch finally块时组织java代码
发布时间:2020-12-14 19:34:31 所属栏目:Java 来源:网络整理
导读:我是一个 java新手.我有一个关于如何在使用try catch finally块时组织java代码的问题.假设我必须阅读一些文本文件并对存储的文件内容进行一些计算.我的代码应该怎么样? 例如 代码1看起来像: public static void main(String[] args){try{//open files usin
我是一个
java新手.我有一个关于如何在使用try catch finally块时组织java代码的问题.假设我必须阅读一些文本文件并对存储的文件内容进行一些计算.我的代码应该怎么样?
例如 代码1看起来像: public static void main(String[] args){ try{ //open files using BufferedReader,read and store the file contents. }catch(IOException e){ e.printStackTrace(); } finally{ //close the files } // do computations on the data } 代码2看起来像: public static void main(String[] args){ try{ //open files using BufferedReader,read and store the file contents. // do computations on the data }catch(IOException e){ e.printStackTrace(); } finally{ //close the files } } 哪两个是更好的编码实践?也应该最后阻止放置 解决方法
使用Java 7和try-with-resources.
try(Connection = pool.getConnection()) { // or any resource you open,like files // ... } // auto closes 这个功能最终接近于弃用 – 一旦添加了这个功能,我个人最终没有找到一个用例,建议你避免使用它.就像函数编程而言,它就像是goto或者可以说是继续,甚至是循环 – 更新的特性使得使用不必要. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |