java - 在 Java 中发生异常时为最终变量分配默认值

标签 java try-catch final

为什么在 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/

相关文章:

c# - 在应用程序的整个生命周期内保持 Lucene IndexWriter 和 IndexSearcher 打开是一种好习惯吗

java - 如何用空值替换\"

java - 为什么要避免使用 final 关键字?

javascript - try-catch 和 async wait js 中的更改顺序?

swift - do - try - catch 代码不尝试或捕获。只是做

Java 可见性 : final static non-threadsafe collection changes after construction

java - Checkstyle 在最终变量的命名约定上与普通 Java 不同?

java - 如何在折线图中的标记 View 上显示 X 标签?

java - java中的一次一密加密

循环中的 Java catch 语句不起作用