研究以下代码:
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
但对我来说,这看起来是不可能的情况。
发布于 2014-09-07 20:36:35
问题是,在这种情况下,编译器是基于语法而不是基于语义工作的。有两种变通方法:第一种是在方法上移动异常句柄:
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;
}
}发布于 2014-09-07 20:22:52
i是最终的,所以它只能赋值一次。编译器可能不够聪明,没有意识到如果抛出异常,第一个赋值就不会发生,如果没有抛出异常,第二个赋值就不会发生。
发布于 2014-09-07 20:38:03
要解决此问题,请在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;
}
}https://stackoverflow.com/questions/25710109
复制相似问题