为什么在 try block 中设置值后,Java 不让我在 catch block 中为最终变量赋值,即使在异常情况下不可能写入最终值。
这是一个演示问题的例子:
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;
}
}
这个问题不难解决,但我想了解为什么编译器不接受这个问题。
在此先感谢您的任何意见!
最佳答案
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.
}
编写一个编译器来处理像这样的非常具体的情况将是一项艰巨的任务——可能有很多这样的情况。
关于java - 在 Java 中发生异常时为最终变量分配默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2603325/