研究这段代码:
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/