我发现Eclipse在报告“本地变量可能未初始化”的错误时存在一种奇怪的二元性。如果我在try/catch块外声明一个变量,在try/catch块内对其进行初始化,然后在try/catch块之后使用它,则通常会出现此错误:
Random r;
try {
r = new AESCounterRNG();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
r.nextInt(); //Error: The local variable r may not have been initialized
这很有道理。我可以通过在声明变量时将其初始化为
null
,或确保程序的控制流永远不会到达下一个语句(如果try/catch块中发生异常),来避免错误。因此,在确实无法继续执行变量初始化失败的情况下,我可以这样做:Random r;
try {
r = new AESCounterRNG();
} catch (GeneralSecurityException e) {
throw new RuntimeException("Initialize secure random number generator failed");
}
r.nextInt(); //No error here
然而,最近我尝试使用 System.exit
来停止程序,而不是使用 RuntimeException
以使我的程序控制台输出更干净。我认为这两者是等效的,因为它们都可以阻止程序继续执行,但我发现 Eclipse 并不同意:
Random r;
try {
r = new AESCounterRNG();
} catch (GeneralSecurityException e) {
System.err.println("Couldn't initialize secure random number generator");
System.exit(1);
}
r.nextInt(); //Error: The local variable r may not have been initialized
当发生异常时,如果执行无法到达
r.nextInt()
,为什么Eclipse仍然会给我“未初始化”的错误?这是Eclipse的一个bug吗,还是在调用System.exit
后仍有方法可以继续执行到r.nextInt()
?
System.exit(1);
后添加一行throw new RuntimeException("never happens");
... 这将满足编译器的要求,在运行时,程序永远不会到达它,因此不会造成任何损害。 - Kevin K