try-catch和final变量

Dev*_*r87 11 java compiler-errors

我有一个非常愚蠢的问题:)

例如,我有以下代码段:

class MyClass {

    public static void main (String[] args) {

        final String status;

        try {
            method1();
            method2();
            method3();
            status = "OK";
        } catch (Exception e) {
            status = "BAD"; // <-- why compiler complains about this line??
        }

    }

    public static void method1() throws Exception {
        // ...
    }

    public static void method2() throws Exception {
        // ...
    }

    public static void method3() throws Exception {
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)

问题在于:为什么编译器抱怨这一行?

IntelliJ IDEA说,那Variable 'status' might already have been assigned to.

但是,正如我所看到的,status = "OK"在特殊情况下,我们永远不会到达线路(我们设置的地方).所以status变量将是BAD,一切都应该没问题.如果我们没有任何例外,那么我们得到OK.我们只会在一段时间内设置此变量.

有什么想法吗?

谢谢你的帮助!

rge*_*man 11

Java编译器看不到你和我看到的内容 - 要么status设置为"OK"或者设置为"BAD".它假定status可以设置抛出异常,在这种情况下,它会被分配两次,并且编译器会生成错误.

要解决此问题,请为try- catchblock 分配临时变量,然后分配final变量一次.

final String status;
String temp;

try {
    method1();
    method2();
    method3();
    temp = "OK";
} catch (Exception e) {
    temp = "BAD";
}

status = temp;
Run Code Online (Sandbox Code Playgroud)

  • @JigarJoshi然后在`Thread`上设置中断标志.只有在IO上阻塞线程(或类似的东西:锁等)时才会发生`InterruptedException`. (2认同)

归档时间:

查看次数:

899 次

最近记录:

10 年,4 月 前