使用try / catch进行最终变量赋值 [英] Final variable assignment with try/catch
问题描述
因为我认为这是一个很好的编程习惯,所以如果打算只编写一次,我会将所有(本地或实例)变量 final
。
Because I believe it is a good programming practice, I make all my (local or instance) variables final
if they are intended to be written only once.
但是,我注意到当变量赋值可以抛出异常时,你不能使变量最终成为:
However, I notice that when a variable assignment can throw an exception you cannot make said variable final:
final int x;
try {
x = Integer.parseInt("someinput");
}
catch(NumberFormatException e) {
x = 42; // Compiler error: The final local variable x may already have been assigned
}
是有没有办法在不诉诸临时变量的情况下做到这一点? (或者这不是最终修饰符的正确位置?)
Is there a way to do this without resorting to a temporary variable? (or is this not the right place for a final modifier?)
推荐答案
这样做的一种方法是引入一个(非 - final
)临时变量,但你说你不想这样做。
One way to do this is by introducing a (non-final
) temporary variable, but you said you didn't want to do that.
另一种方法是将代码的两个分支移动到一个函数中:
Another way is to move both branches of the code into a function:
final int x = getValue();
private int getValue() {
try {
return Integer.parseInt("someinput");
}
catch(NumberFormatException e) {
return 42;
}
}
这是否实用取决于具体用途case。
Whether or not this is practical depends on the exact use case.
总而言之,只要 x
是一个适当范围的局部变量,最实用一般方法可能是非 - 最终
。
All in all, as long as x
is a an appropriately-scoped local variable, the most practical general approach might be to leave it non-final
.
如果另一方面, x
是一个成员变量,我的建议是在初始化期间使用非 final
临时:
If, on the other hand, x
is a member variable, my advice would be to use a non-final
temporary during initialization:
public class C {
private final int x;
public C() {
int x_val;
try {
x_val = Integer.parseInt("someinput");
}
catch(NumberFormatException e) {
x_val = 42;
}
this.x = x_val;
}
}
这篇关于使用try / catch进行最终变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!