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?)
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 create a function for both branches of the code:
Whether or not this is practical depends on the exact use case.
All in all, as long as
xis an appropriately-scoped local variable, the most practical general approach might be to leave it non-final.If, on the other hand,
xis a member variable, my advice would be to use a non-finaltemporary during initialization: