为什么Java不让我在设置try块中的值后为catch块中的final变量赋值,即使在发生异常的情况下不可能写入最终值。
这是一个演示问题的示例:
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;
}
}
这个问题并不难解决,但我想了解为什么编译器不接受这个。
提前感谢您的任何投入!