Why won't Java let me assign a value to a final variable in a catch block after setting the value in the try block, even if it is not possible for the final value to be written in case of an exception.
Here is an example that demonstrates the problem:
public class FooBar {
private final int foo;
private FooBar() {
try {
int x = bla();
foo = x; // In case of an exception this line is never reached
} catch (Exception ex) {
foo = 0; // But the compiler complains
// that foo might have been initialized
}
}
private int bla() { // You can use any of the lines below, neither works
// throw new RuntimeException();
return 0;
}
}
The problem is not hard to work around, but I would like to understand why the compiler does not accept this.
Thanks in advance for any inputs!
Exceptioncould it be possible for something to occur just after/duringfoo = xthat would throw an exception? Maybe the compiler is "playing it safe"?foo = bla();it is not possible to result in an exception and a correct assignment, since it is still two statements. I suspect that greim and FromCanada are right about the compiler playing safe (or being short sighted), because this is really a corner case which is only applicable if the assignment is the last non side effect free statement.