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; } }
NPE Nov 28 '12 at 11:38 2012-11-28 11:38
source share