gpt4 book ai didi

java - 如何避免 "local variable may not have been initialized"Java 编译错误? (是的,认真的!)

转载 作者:搜寻专家 更新时间:2023-11-01 01:12:30 25 4
gpt4 key购买 nike

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

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

甚至

throw abandonEverythingAndDie();

private static AssertionError abandonEverythingAndDie() {
System.exit(1);
throw new AssertionError("impossible to reach this place");
}

关于java - 如何避免 "local variable may not have been initialized"Java 编译错误? (是的,认真的!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30076793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com