使用try-catch-finally块时组织java代码
我是java新手。在使用try-catch-finally块时,我有一个关于如何组织java代码的问题。假设我必须读取一些文本文件,并对存储的文件内容进行一些计算。我的代码应该是什么样子 比如说 代码1看起来像:使用try-catch-finally块时组织java代码,java,coding-style,try-catch,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.
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
}
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
}
}
代码2看起来像:
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
}
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
}
}
哪一种是更好的编码实践?最后也应该把方块放在刚过的地方
try catch或者它可以放在末端。最后一个块应该放在try catch之后。您想在哪里对数据进行计算取决于您。。。但是如果您将它放在try-catch块之后,即使抛出异常,它也会尝试计算,除非您使用条件 使用Java 7并尝试使用资源
try(Connection = pool.getConnection()) { // or any resource you open, like files
// ...
} // auto closes
此功能几乎不推荐使用
finally
——我个人还没有发现添加此功能后finally
的用例,建议您避免使用。就函数编程而言,这就像是goto
,或者可以说是continue
,甚至是for
循环,因为更新的特性使使用变得不必要。应该使用第二种方法,因为它将更容易对数据进行计算,而不会遇到可变范围的问题。然而,这两种方法都可以根据需要进行的计算而工作。第二种方法
对于异常,您可以在检测到问题并且捕获到异常的时间点抛出异常,而不是在早期问题不再影响代码执行的第一个时间点抛出异常。可能是在catch块中进行一些处理,并使用finally块进行一些清理
在第一个代码示例中,捕获后的代码仍然受到导致异常的错误的影响。所以你很早就赶上了。这意味着您可能必须在其周围添加if语句,这不必要地增加了函数的复杂性 这取决于您的系统具体情况,我看到两种可能的情况: 1) 文件很大。那你就不能把它载入内存了。你们应该一张一张地读文件的图片,并在每一张图片上做你们的逻辑。这将防止内存耗尽 2) 文件很小。然后,您可以选择是遵循第一个案例还是读取memmory中的文件,关闭它,然后处理它
还有一个注意事项:文件未关闭时,其他进程无法访问它。如果您的逻辑很长,那么这可能是一个问题,在这种情况下,先读取并关闭文件会更好。方法2,因为如果要对其进行计算,您可能需要数据。在
catch
块中调用e.printStackTrace()
不会处理异常。这是经典的。我只会把需要的东西放在try catch里面。读取该文件将引发异常,因此我将其放入try catch中。如果你的计算是这样的,那么把它们放在一个单独的try-catch中,如果不是,就把它们移到外面。所以我有点推荐代码1@Asaph我真的因为“永远不应该发生,打印到控制台”而失去了一份工作,而这本应该是“永远不应该发生,崩溃”。谢谢你的建议。我会试试看。