【发布时间】:2012-03-13 09:15:54
【问题描述】:
我想安全地关闭资源而不是传播异常。到目前为止,我想出了两个解决方案。
解决方案 1
FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
// R/W operation with files
} finally {
// close sourceDir, targetDir, br, bw
}
解决方案 2
FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
// R/W operation with files
} catch (IOException e) {
throw e;
} finally {
// close sourceDir, targetDir, br, bw
}
我不喜欢第二个解决方案中的throw e,但try-finally 对我来说似乎有点不寻常,所以我不确定我应该使用哪一个。或者有什么更好的方法吗?
【问题讨论】:
-
您的解决方案 2 与解决方案 1 相同。仅当您在
catch-block 中添加更多代码(例如,记录异常)时才会有所不同。 -
我知道但再次抛出异常是不必要的代码。在这种情况下,我不想在这里登录...我想知道 try-finally 是否可以。
-
是的,绝对没问题。只是想你可能会认为这两个代码 sn-ps 的行为不同。
-
@PhilippWendler 不,我的问题是关于语法,但我忘了提。
标签: java exception file-io syntax exception-handling