繁体   English   中英

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

[英]Assigning a default value to a final variable in case of an exception in Java

为什么在设置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;
    }
}

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

提前感谢任何输入!

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.
}

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

要成为一名学徒, Thread.stop(Throwable)可能会在try块分配后立即抛出异常。

但是,具有明确分配和相关术语的规则足够复杂。 检查JLS。 尝试添加更多规则会使语言复杂化并且不会带来显着的好处。

抛出Error怎么样?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM