Below does not compile.

public class Foo {
final String bar;

Foo() {
try {
bar = “”;
} catch (Exception e) {

}
}
}

Let us rewrite the same code as

public class Foo {
final String bar;

Foo() throws Exception {
bar = “”;
}
}

This works. Why the first one did not compile?

Time to take a look at the final key word. When a variable is declared as final and is not initialized, it should have a value by the time the constructor completes or when the static block completes in case of a static variable.

In the first case, why the compiler freaks out when the initialization is wrapped in a try catch block?

When you wrap something within a try catch block, you are telling the compiler that there is a potential that the code within the block might throw an exception. So, when the compiler sees a final variable inside a try catch block, it reasons that what if an exception is thrown? Then the final variable is left uninitialized. So, there is a possibility that when the constructor completes, the final variable might still be uninitialized. Hence the compile time error.

Why does it work in the second case?

Well, here if an exception is thrown, the object is never created. So, there is no way the final variable is left uninitialized.

Advertisements