为什么在设置try块中的值之后,Java不允许我在catch块中为最终变量赋值,即使在异常的情况下不能写入最终值。 / p>
以下是演示此问题的示例:
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;
}
}
问题并不难解决,但我想理解为什么编译器不接受这个。
提前感谢任何输入!
答案 0 :(得分: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.
}
编写一个编译器来处理这样的非常具体的案例将是一项艰巨的任务 - 可能会有很多这样的事情。
答案 1 :(得分:2)
要成为一名学究者,Thread.stop(Throwable)
可能会在尝试块分配后立即抛出异常。
但是,具有明确分配和相关术语的规则足够复杂。检查JLS。试图添加更多规则会使语言复杂化并且不会带来显着的好处。
答案 2 :(得分:0)
抛出Error
怎么样?