8

例外が発生した場合に最終値を書き込むことができない場合でも、Java が try ブロックに値を設定した後、catch ブロックの最終変数に値を代入させないのはなぜですか。

問題を示す例を次に示します。

public class FooBar {

    private final int foo;

    private FooBar() {
        try {
            int x = bla();
            foo = x; // In case of an exception this line is never reached
        } catch (Exception ex) {
            foo = 0; // But the compiler complains
                     // that foo might have been initialized
        }
    }

    private int bla() { // You can use any of the lines below, neither works
        // throw new RuntimeException();
        return 0;
    }
}

この問題を回避するのは難しくありませんが、コンパイラがこれを受け入れない理由を理解したいと思います。

ご意見をお寄せいただきありがとうございます。

4

3 に答える 3

7
try {
    int x = bla();
    foo = x; // In case of an exception this line is never reached
} catch (Exception ex) {
    foo = 0; // But the compiler complains
             // that foo might have been initialized
}

その理由は、例外が初期化される前にのみスローできるとコンパイラが推測できないためですfoo。この例は、それが真であることが明らかな特殊なケースですが、次のことを考慮してください。

try {
    int x = bla();
    foo = x; // In case of an exception this line is never reached...or is it?
    callAnotherFunctionThatThrowsAnException();  // Now what?
} catch (Exception ex) {
    foo = 0; // But the compiler complains
             // that foo might have been initialized,
             // and now it is correct.
}

このような非常に特殊なケースを処理するコンパイラを作成することは、膨大な作業になります。おそらく非常に多くのケースがあります。

于 2010-04-08T21:03:49.933 に答える
2

衒学者になるにThread.stop(Throwable)は、try ブロックの割り当ての直後に例外をスローする可能性があります。

ただし、明確な割り当てと関連用語を含むルールは十分に複雑です。JLSを確認してください。さらにルールを追加しようとすると、言語が複雑になり、大きなメリットが得られません。

于 2010-04-08T22:17:33.893 に答える
0

スローはErrorどうですか?

于 2010-04-08T20:45:58.833 に答える