【问题标题】:try-catch and final variables [duplicate]try-catch 和 final 变量
【发布时间】:2015-06-29 18:43:45
【问题描述】:

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

例如,我有以下代码sn-p:

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。我们将只设置一次这个变量。

对此有什么想法吗?

感谢您的帮助!

【问题讨论】:

  • 编译器不是那么聪明,如果你声明该方法可能会抛出异常,编译器不会费力检查它,所以为了简单起见,它不允许这样的事情发生

标签: java compiler-errors


【解决方案1】:

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;

【讨论】:

  • 我认为它仍然是有效错误,如果这个线程被中断并在分配后立即抛出InterruptedException 怎么办
  • @JigarJoshi 它不能抛出InterruptedException(可能是别的东西,但不是那个,也可能不在这段代码中)。
  • 如果这是在单独的线程中并且被interrupt()调用
  • @JigarJoshi 然后将在Thread 上设置中断标志。 InterruptedException 只会在线程被 IO 阻塞(或类似的东西:锁等)时才会发生。
  • @Sotirios 你是对的 - 谢谢!
【解决方案2】:

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

以此为例:

final String status;

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

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

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

【讨论】:

  • 变量是最终的。禁止重新分配。
  • @swinkler 这就是我要表达的观点。发生错误是因为上面显示的代码是可能的。伙计,现在 StackOverflow 怎么了..
猜你喜欢
  • 2015-12-07
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
相关资源
最近更新 更多