A good programming practice is to make a variable final whenever possible. However, following this principle can sometimes be tricky. One such case is when the variable/field is initialized with return of a function that throws exception. Let me explain using an example. Suppose, you have classes Foo and Bar as follows:

class Foo{
  private Foo(){}

  public static Foo createFoo() throws Exception{

  }
}

class Bar{
  private final Foo foo;

  //This will not work. It will give the error "variable foo might not have been initialized.
  public Bar(){
     try{
      foo = Foo.createFoo();
     }catch(Exception e){
      System.err.println("foo cannot be initialized");
     }
  }
}

As you can see that the variable foo, in a Bar object is final. Function createFoo() creates a Foo object. As this method can throw an exception, the code for class Bar will not compile, raising an error “variable foo might not have been initialized.

The problem is that the compiler has no way of making sure that the variable foo will be assigned after the constructor for Bar finishes (foo will not be initialized if createFoo() throws an exception). How can you solve this compilation error?

Here is how: Write another function that wraps call to the function createFoo() and the associated exception handling.

 

class Bar{
  ...
  public Bar(){
      foo = createFooWrapper();
  }

  private Foo createFooWrapper(){
     try{
      return Foo.createFoo();
     }catch(Exception e){
      System.err.println("foo cannot be initialized");
     }
     return null;
  }
}

In case the exception occurs, foo will be null, else it would be what createFoo()  returns.