Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final variable assignment with try/catch

Tags:

java

final

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?)

like image 290
dtech Avatar asked Nov 28 '12 11:11

dtech


People also ask

Can you access variables from TRY in catch?

So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

What is final in try catch?

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

Is it necessary to use catch after try?

is it necessary to put catch after try block ? Nope, not at all. Its not mandatory to put catch after try block, unless and until the try block is followed by a finally block. Just remember one thing, after try, a catch or a finally or both can work.


1 Answers

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;   } } 
like image 122
NPE Avatar answered Sep 21 '22 00:09

NPE