在您说这个问题已经被无数次回答之前,这是我的代码片段:
final int x;
try {
x = blah();
} catch (MyPanicException e) {
abandonEverythingAndDie();
}
System.out.println("x is " + x);
如果调用abandonEverythingAndDie()
具有结束整个程序执行的作用(例如,因为它调用System.exit(int)
),那么x
无论何时使用它,总是将其初始化。
在当前的Java语言中,是否有一种方法可以通知编译器abandonEverythingAndDie()
它永远不会将控制权返回给调用者,从而使编译器对变量初始化感到满意?
我不想要
final
关键字x
在声明时初始化,println
的范围内try...catch
。通过向编译器提供一些额外的信息来欺骗一些用户:
final int x;
try {
x = blah();
} catch (MyPanicException e) {
abandonEverythingAndDie();
throw new AssertionError("impossible to reach this place"); // or return;
}
System.out.println("x is " + x);
您还可以使abandonEverythingAndDie()
return发生某种变化(仅从语法上讲,它当然永远不会返回),然后调用return abandonEverythingAndDie()
:
final int x;
try {
x = blah();
} catch (MyPanicException e) {
return abandonEverythingAndDie();
}
System.out.println("x is " + x);
和方法:
private static <T> T abandonEverythingAndDie() {
System.exit(1);
throw new AssertionError("impossible to reach this place");
}
甚至
throw abandonEverythingAndDie();
与
private static AssertionError abandonEverythingAndDie() {
System.exit(1);
throw new AssertionError("impossible to reach this place");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句