【问题标题】:variable might already have been assigned when it cannot be assigned变量在无法赋值时可能已经赋值
【发布时间】:2014-09-07 12:22:02
【问题描述】:

研究这段代码:

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        try {
            i = method1();
        } catch (IOException ex) {
            i = 0;  // error: variable i might already have been assigned
        }
    }

    static int method1() throws IOException {
        return 1;
    }
}

编译器说java: variable i might already have been assigned

但对我来说,这似乎是不可能的情况。

【问题讨论】:

标签: java try-catch final


【解决方案1】:

问题在于,在这种情况下,编译器是基于语法而不是基于语义的。 有2个解决方法: 首先基于在方法上移动异常句柄:

package com.java.se.stackoverflow;

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        i = method1();
    }

    static int method1() {
        try {
            return 1;
        } catch (Exception ex) {
            return 0;
        }
    }
}

使用临时变量的第二个基础:

package com.java.se.stackoverflow;

import java.io.IOException;

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        int tempI;
        try {
            tempI = method1();
        } catch (IOException ex) {
            tempI = 0;
        }
        i = tempI;
    }

    static int method1() throws IOException {
        return 1;
    }
}

【讨论】:

  • 我遇到的关于 SO 的最佳答案之一。
【解决方案2】:

要解决这个问题,请在 try catch 块中使用局部变量,然后将该结果分配给实例变量。

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        int tmp;
        try {
            tmp = method1();
        } catch (IOException ex) {
            tmp = 0;
        }
        i = tmp;
    }

    static int method1() throws IOException {
        return 1;
    }
}

【讨论】:

  • mmm.. 谢谢,但我不想克服这个问题))关于如何可能的问题
【解决方案3】:

i 是最终的,因此只能分配一次。编译器可能不够聪明,无法意识到如果抛出异常,则不会进行第一次赋值,如果未抛出异常,则不会进行第二次赋值。

【讨论】:

  • 是的,但我的情况像 if else
  • no.. 它不像 if else。可能会发生你的 i 被分配然后你的代码抛出异常
  • @Adi 在我的情况下这是不可能的
  • 是的。但编译器不明白这一点。就像 Eran 说的那样,它还不够“聪明”:)。
【解决方案4】:

https://bugs.openjdk.java.net/browse/JDK-6326693?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel

看起来像 JDK 错误。现在状态 - 已修复。但是我找不到哪个版本。

【讨论】:

  • 不,这是一个错误,当最终变量被分配到多个 catch 块中时,而不是在 trycatch 中。此外,此错误已在 Java 8 中修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 2020-10-11
  • 2020-02-21
相关资源
最近更新 更多