如何避免“局部变量可能尚未初始化”Java编译错误? (是的,认真的!)

2024-03-06

在你说这个问题已经被回答过很多次之前,这里是我的代码片段:

final int x;
try {
    x = blah(); 
} catch (MyPanicException e) {
    abandonEverythingAndDie();
}
System.out.println("x is " + x);

如果调用abandonEverythingAndDie()具有结束整个程序执行的效果(比如说因为它调用System.exit(int)), 然后x每当使用时总是被初始化。

当前的 Java 语言中是否有一种方法可以通过通知编译器对变量初始化感到满意abandonEverythingAndDie()是一个永远不会将控制权返回给调用者的方法吗?

I do not想要

  • 去除final关键词
  • 初始化x声明的同时,
  • 也不把println在范围内try...catch block.

并非没有通过向编译器提供一点额外信息来作弊:

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 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");
}

or even

throw abandonEverythingAndDie();

with

private static AssertionError abandonEverythingAndDie() {
    System.exit(1);
    throw new AssertionError("impossible to reach this place");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何避免“局部变量可能尚未初始化”Java编译错误? (是的,认真的!) 的相关文章

随机推荐