try-catch 和 final 变量

try-catch and final variables

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

例如,我有以下代码片段:

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

}

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

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

但是,正如我所见,在特殊情况下我们永远不会到达线(我们设置 status = "OK" 的地方)。所以 status 变量将是 BAD 并且一切都应该没问题。如果我们没有任何异常,那么我们会得到 OK。我们一次只设置一次这个变量。

对此有什么想法吗?

感谢您的帮助!

如果导致异常的代码发生在status = "OK"之后怎么办?您收到错误的原因似乎很明显。

以此为例:

final String status;

try {
    status = "OK":
    causeException();
}catch(Exception e) {
    status = "BAD";
}

void causeException() throws Exception() {
    throw new Exception();
}

这将导致重新分配变量,这就是您收到错误的原因

Java 编译器看不到你我所看到的——status 被设置为 "OK" 或被设置为 "BAD"。它假定 status 可以设置 并且 抛出异常,在这种情况下它被赋值两次,并且编译器产生错误。

要解决此问题,请为 try-catch 块分配一个临时变量,然后再分配一次 final 变量。

final String status;
String temp;

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

status = temp;