在Java中发生异常的情况下,为默认值分配最终变量

Alf*_*nso 8 java final try-catch

为什么在设置try块中的值之后,Java不允许我为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题并不难解决,但我想理解为什么编译器不接受这个.

提前感谢任何输入!

dan*_*ben 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
}
Run Code Online (Sandbox Code Playgroud)

原因是编译器无法推断异常只能在初始化之前抛出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.
}
Run Code Online (Sandbox Code Playgroud)

编写一个编译器来处理像这样的非常具体的情况将是一个巨大的任务 - 可能有很多.