例外が発生した場合に最終値を書き込むことができない場合でも、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;
}
}
この問題を回避するのは難しくありませんが、コンパイラがこれを受け入れない理由を理解したいと思います。
ご意見をお寄せいただきありがとうございます。