java - 无法赋值时,变量可能已经赋值

标签 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 assigned
        }
    }

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

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

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

最佳答案

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

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

关于java - 无法赋值时,变量可能已经赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710109/

相关文章:

java - Android : How can i interface between . java文件和GSOAP

java - 将字符串列表拆分为 map 列表

java - 非最终 - 不可变类

java - 在 JButton 的 actionperformed 中需要最终变量吗?

c++11 - C++0x 中的最终虚函数

java - 如何在不使用文件路径的情况下引用图像?

java - 方法参数困惑

python - 用于包装尝试的通用装饰器除了在 python 中?

vbscript - VBScript 中的 Try-Catch-End Try 似乎不起作用

java - 如何循环 try catch 语句?