Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法分配变量时,该变量可能已被分配_Java_Try Catch_Final - Fatal编程技术网

Java 无法分配变量时,该变量可能已被分配

Java 无法分配变量时,该变量可能已被分配,java,try-catch,final,Java,Try Catch,Final,研究此代码: 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 assi

研究此代码:

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可能已经被赋值了


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

i
是最终的,所以只能分配一次。编译器可能不够聪明,无法意识到如果抛出异常,第一个赋值将不会发生,如果没有抛出异常,第二个赋值将不会发生。

问题是,在这种情况下,编译器是基于语法而非语义工作的。 有两种变通方法: 首先基于在方法上移动异常句柄:

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;
    }
}

要解决此问题,请在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;
    }
}


看起来像是JDK bug。现在状态已修复。但我无法从哪个版本中找到答案。

是的,但我的情况就像艾尔塞诺。。它不像其他的东西。可能会发生这样的情况:您的i被分配,然后您的代码抛出exception@Adi在我的情况下,这是不可能的。但编译器不明白这一点。正如Eran所说,它“不够聪明”:)这是对同一个问题的一个非常好的回答:这里已经介绍了解决方法。。谢谢,但我不想克服这个问题)关于它如何可能的问题否,当在多个catch块中分配最终变量时,这是一个错误,而不是在
try
catch
中。另外,这个错误在Java8中得到了修复。这是我遇到的最好的答案之一。