【问题标题】:Proper way to close files and propagate exception in the same time同时关闭文件和传播异常的正确方法
【发布时间】: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


【解决方案1】:

如果您想记录异常和/或将其包装在运行时异常中并抛出它,第二种解决方案可能会很有用。

【讨论】:

    【解决方案2】:

    选项 1 完全正确。 try ... finally 通常用于此目的。

    您甚至可以将return 放入您的try 块中,Java 将处理您的finally 然后返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2013-03-06
      • 2010-09-13
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多