scv*_*scv 5 java coding-style try-catch
我是一个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
}
Run Code Online (Sandbox Code Playgroud)
代码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
}
}
Run Code Online (Sandbox Code Playgroud)
哪两个是更好的编码实践?也应该在try catch之后最终阻止放置,或者它可以放在最后.
使用 Java 7 和 try-with-resources。
try(Connection = pool.getConnection()) { // or any resource you open, like files
// ...
} // auto closes
Run Code Online (Sandbox Code Playgroud)
此功能接近弃用- 我个人还没有找到添加此功能后的finally用例,建议您避免使用它。finally就函数式编程而言,它就像goto或可以说是循环continue,甚至是for循环——新的功能使得使用变得不必要。