Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not initialize static final variable in try/catch

I am trying to initialize a static final variable. However, this variable is initialized in a method which can throw exception, therefor, I need to have inside a try catch block.

Even if I know that variable will be either initialized on try or on catch block, java compiler produces an error

The final field a may already have been assigned

This is my code:

public class TestClass {

  private static final String a;

  static {
    try {
      a = fn(); // ERROR
    } catch (Exception e) {
      a = null;
    }
  }

  private static String fn() throws Exception {
    throw new Exception("Forced exception to illustrate");
  }

}

I tried another approach, declaring it as null directly, but it shows a similar error (In this case, it seems totally logic for me)

The final field TestClass.a cannot be assigned

public class TestClass {

  private static final String a = null;

  static {
    try {
      a = fn(); // ERROR
    } catch (Exception e) {
    }
  }

  private static String fn() throws Exception {
    throw new Exception("Forced exception to illustrate");
  }

}

Is there an elegant solution for this?

like image 264
Mayday Avatar asked Apr 23 '18 09:04

Mayday


People also ask

Do you have to initialize final variables in Java?

We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable can only be initialized once, either via an initializer or an assignment statement.

What is final in try catch?

The code opens a file and then executes statements that use the file; the finally -block makes sure the file always closes after it is used even if an exception was thrown.

How do you access variable outside try catch?

In your above example, the variable len is declared inside the try block, its scope is only within the try block and can't be accessed outside the try block. You should declare the len variable even before the try block, so that it can be accessed in the finally block. Save this answer.

Can we change final variable in Java?

1) Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant).


1 Answers

You can assign the value to a local variable first, and then assign it to the final variable after the try-catch block:

private static final String a;

static {

    String value = null;
    try {
        value = fn();
    } catch (Exception e) {
    }
    a = value;

}

This ensures a single assignment to the final variable.

like image 81
Eran Avatar answered Oct 01 '22 08:10

Eran