I have some code like:
final int var1;
if ( isSomethingTrue ) {
var1 = 123;
} else {
throwErrorMethod();
}
int var2 = var1;
And throwErrorMethod is defined something like:
private void throwErrorMethod() throws Exception{
throw new Exception();
}
And I get a blank final field may not have been initialized
compile error for the var2 = var1
statement. If I inline the method, compilation is fine!
throws Exception
on the method called?may
in it stops compilation?!?No, the compiler doesn't determine that the throwErrorMethod
will never complete normally. There's nothing in the specification to suggest it should. Unfortunately there's no way to indicate that a method will never return normally.
It's only "may" because there's a potential execution path which doesn't initialize the variable. The presence of such an execution path is defined to be an error.
You may find this pair of blog posts (part 1; part 2) by Eric Lippert interesting. It's about C# rather than Java, but it's the same principle.