0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Effective Java(第3版) 項目9 try-finally よりも try-with-resources を選ぶ

Last updated at Posted at 2021-05-09

クローズしなければならない資源に対しては、Java7で導入された try-with-resources を使用するべき、という内容です。

記載内容

結論としては、クローズが必要な資源を使用する場合、try-with-resourcesを使用するべき。

try-finally の欠点

Java6以前は、資源の適切なクローズを保証するだったが、以下の欠点がある

  • 間違えやすい(2007時点でJavaライブラリ内の3分の2が間違えているほど)
  • finally内で発生した例外が最初に発生した例外を隠してしまう

try-with-resources の利点

try-finally の問題が一挙に解決している。

  • 資源はAutoCloseableインタフェースを実装する必要が有る
  • closeで例外が発生しても、最初の例外が優先される。getSuppressedメソッドで、closeで発生した例外も取得可能
  • catch節を記載することも可能

考察

既に try-with-resources のメリットが広く認識されており、特に問題ないと思います。

著者が間違えたというJava puzzlersのコードは以下の様なものです。

InputStream in = null;
OutputStream out = null;
try {
    in = new FileInputStream(src);
    out = new FileOutputStream(dest);
    byte[] buf = new byte[1024];
    int n;
    while ((n = in.read(buf)) > 0)
        out.write(buf, 0, n);
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {} // クローズエラーに対して出来ることはない
    }
    if (out != null) {
        try {
            out.close();
        } catch (IOException e) {} // クローズエラーに対して出来ることはない
    }
} 

何を間違えているか明示されていませんので確実ではないですが、
メインのIO処理で例外が発生せず、クローズで例外が出た場合、
その例外が握りつぶされることが問題なのかと思います。

確かに、try-with-resourcesなしで、これを綺麗に書くのは難しいですね・・・

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?