我有一个非常愚蠢的问题要问你 :)
比如,我有以下代码片段:
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说:
变量'status'可能已经被赋值
。但是,据我所见,在异常情况下我们永远不会到达设置
status =“OK”
的那一行代码。因此,status
变量将是BAD
,一切应该都没问题。如果我们没有任何异常,那么我们就会得到OK
。而且我们只会一次性地设置这个变量。对此有什么想法吗?
谢谢你的帮助!