1
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 5 years have passed since last update.

Java6でのリソースと例外処理

Posted at
修正前
InputStream in = null;
try {
    in = new FileInputStream("test.txt");
    // stream操作
} catch (IOException e) {
    // error処理
} finally {
    try { // 必要に応じて
        if (in != null) {
            in.close();
        }
    } catch (IOException e) {
    }
}

というコードをよく見かける(定石?だったはず)が、そもそも、Stream(というかオブジェクト)のインスタンス生成に失敗すると、絶対にinにはnullしか入り得ない。
そのため、finallyブロックでのif文は必ずin==nullとなり、無駄である。
スコープを考えた場合にも不自然に思える。
(コードカバレッジを取ると、絶対に通せないため、C1が上がらない)

Java7ならば、try-with-resourceを使用することで、綺麗になるだろうが、6以前では以下のようにするベキではなかろうか?

修正後
try {
    InputStream in = new FileInputStream("test.txt");
    try {
        // stream操作
    } finally {
        try { // 必要に応じて
        in.close();
        } catch (IOException e) {
        }
    }
} catch (IOException e) {
    // error処理
}

因みに、finallyでのtry-catchは、closeで投げられるIOExceptionを握りつぶすか否かに依るため、「必要に応じて」とコメントしている

1
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
1
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?