gst*_*low 8 java final try-catch
研究这段代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
编译器说 java: variable i might already have been assigned
但对我来说,这似乎是不可能的情况.
i是最终的,因此只能分配一次.编译器可能不够聪明,无法实现如果抛出异常,则不会发生第一个赋值,如果不抛出异常,则不会发生第二个赋值.
小智 8
问题在于,在这种情况下,编译器基于语法而不是基于语义的.有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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
二,使用temporar变量:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2023 次 |
| 最近记录: |