使用 try/catch 进行最后的变量赋值

因为我相信这是一个很好的编程实践,所以我将所有(本地或实例)变量 final,如果它们打算只写一次的话。

然而,我注意到当一个变量赋值可以抛出一个异常时,你不能让这个变量成为 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
}

有没有一种方法可以做到这一点,而不诉诸于一个临时变量?(或者这不是最后修饰语的正确位置?)

33099 次浏览

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

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.

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

No it is not the right place, imagine you got more then 1 Statement in your try and catch block, the first one says : x = 42. After some others Statements the try block fails, and it goes to the catch block, where your Saying x = 30. Now you defined x twice.