Final assignment of a variable using try / catch

Since I believe this is good programming practice, I do all of my (local or instances) final variables if they are intended to be written only once.

However, I notice that when assigning a variable can throw an exception, you cannot make the specified 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 the final modifier?)

+48
java final
Nov 28 '12 at 11:33
source share
2 answers

One way to do this is to enter a temporary variable ( final ), but you said you did not want to do this.

Another way is to move both code branches to a function:

 final int x = getValue(); private int getValue() { try { return Integer.parseInt("someinput"); } catch(NumberFormatException e) { return 42; } } 

No matter how real it is, it depends on the specific use case.

In the general case, if x is a local region with a corresponding region, the most practical general approach may be to leave it non- final .

If, on the other hand, x is a member variable, my advice would be to use non final 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; } } 
+41
Nov 28 '12 at 11:38
source share

No, this is not a suitable place, imagine that you got more than 1 expression in your try and catch block, the first one says: x = 42. After some other statements, the try block does not work, and it goes into the catch block, where your statement is x = 30. Now you have identified x twice.

+2
Nov 28 '12 at 11:39
source share



All Articles