这段Java拼图代码有什么问题



在新的第三版Effective Java中,Joshua Bloch提到了Java Puzzlers的一段代码(这是关于在try-final中关闭资源(:

首先,我在Java Puzzlers的第88页上弄错了,多年来没有人注意到。事实上,在 Java 库中,三分之二的 close 方法的使用在 2007 年是错误的。

但我不确定这里是哪一部分错了?

} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException ex) {
      // There is nothing we can do if close fails
    }
  }
  if (out != null) {
    try {
      out.close();
    } catch (IOException ex) {
      // Again, there is nothing we can do if close fails
    }
  }
}

这是此代码的新版本:

try {
  OutputStream out = new FileOutputStream(dst);
  try {
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while ((n = in.read(buf)) >= 0) out.write(buf, 0, n);
  } finally {
    out.close();
  }
} finally {
  in.close();
}

如果in.close()抛出一个未被 catch 块捕获的异常(例如任何RuntimeException(,out甚至不会尝试关闭。

虽然在给定的示例中(使用最有可能IOException的正常流(,但这不是一个大问题,但代码不正确,学习这样编写可能会导致更严重的问题。

最新更新