[英]Final variable assignment with try/catch
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. 因为我相信这是一个良好的编程习惯,我把我所有的(本地或实例变量) final
,如果他们的目的是只能写入一次。
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?) (或者这不是最终修饰符的正确位置吗?)
One way to do this is by introducing a (non- final
) temporary variable, but you said you didn't want to do that. 一种实现方法是引入(非final
)临时变量,但是您说您不想这样做。
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;
}
}
Whether or not this is practical depends on the exact use case. 这是否可行取决于确切的用例。
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: 另一方面,如果x
是成员变量,我的建议是在初始化期间使用非final
临时变量:
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 and catch块中有1条以上的语句,第一个语句是:x =42。在其他语句之后,try块失败了,然后转到catch块,在此处假设x =30。现在您定义了x两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.