java - 这段 Java Puzzlers 代码有什么问题?

标签 java try-catch try-catch-finally effective-java try-finally

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

For starters, I got it wrong on page 88 of Java Puzzlers, and no one noticed for years. In fact, two-thirds of the uses of the close method in the Java libraries were wrong in 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 block 捕获的异常(例如任何 RuntimeException),out 将不会甚至试图关闭。

虽然在给定的示例中(对于最有可能出现 IOException 的普通流)这不是一个大问题,但代码不正确并且学习这样编写它可能会导致更严重的问题路。

关于java - 这段 Java Puzzlers 代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449093/

相关文章:

java - jdk1.7.0中内存泄漏

java - 类加载器、类差异

java - Spring Data Jpa 保存测试失败

python - 无论如何,最终是否确保某些代码以原子方式运行?

java - catch是java中的一个方法吗?

java - 以增量方式生成随机数

c# - 第一次抛出 SocketException,但我的 catch 不起作用

javascript - 在 try block 中使用 try 来捕获不同的错误是一个好习惯吗? - JavaScript

javascript - Node.js 捕获生成后引发的 ENOMEM 错误

java - catch 和 finally 中 return 语句的行为