在您说这个问题已经被回答了很多次之前,这是我的代码片段:
final int x;
try {
x = blah();
} catch (MyPanicException e) {
abandonEverythingAndDie();
}
System.out.println("x is " + x);
Run Code Online (Sandbox Code Playgroud)
如果调用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);
Run Code Online (Sandbox Code Playgroud)
你也可以abandonEverythingAndDie()返回一些东西(只在语法上,它当然永远不会返回),并调用return abandonEverythingAndDie():
final int x;
try {
x = blah();
} catch (MyPanicException e) {
return abandonEverythingAndDie();
}
System.out.println("x is " + x);
Run Code Online (Sandbox Code Playgroud)
和方法:
private static <T> T abandonEverythingAndDie() {
System.exit(1);
throw new AssertionError("impossible to reach this place");
}
Run Code Online (Sandbox Code Playgroud)
甚至
throw abandonEverythingAndDie();
Run Code Online (Sandbox Code Playgroud)
同
private static AssertionError abandonEverythingAndDie() {
System.exit(1);
throw new AssertionError("impossible to reach this place");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |