【发布时间】:2015-06-29 18:43:45
【问题描述】:
我有一个非常愚蠢的问题要问你:)
例如,我有以下代码sn-p:
class MyClass {
public static void main (String[] args) {
final String status;
try {
method1();
method2();
method3();
status = "OK";
} catch (Exception e) {
status = "BAD"; // <-- why compiler complains about this line??
}
}
public static void method1() throws Exception {
// ...
}
public static void method2() throws Exception {
// ...
}
public static void method3() throws Exception {
// ...
}
}
问题在里面:为什么编译器会抱怨这一行?
IntelliJ IDEA 说,Variable 'status' might already have been assigned to。
但是,正如我所见,在特殊情况下,我们永远不会到达线路(我们设置status = "OK")。所以status 变量将是BAD,一切都应该没问题。如果我们没有任何异常,那么我们会得到OK。我们将只设置一次这个变量。
对此有什么想法吗?
感谢您的帮助!
【问题讨论】:
-
编译器不是那么聪明,如果你声明该方法可能会抛出异常,编译器不会费力检查它,所以为了简单起见,它不允许这样的事情发生
标签: java compiler-errors