I am quite convinced that here
final int i;
try { i = calculateIndex(); }
catch (Exception e) { i = 1; }
i
cannot possibly have already been assigned if control reaches the catch-block. However, Java compiler disagrees and claims the final local variable i may already have been assigned
.
Is there still some subtlety I am missing here, or is this just a weakness of the model used by the Java Language Specification to identify potential reassignments? My main worry are things like Thread.stop()
, which may result in an exception being thrown "out of thin air," but I still don't see how it could be thrown after the assignment, which is apparently the very last action within the try-block.
The idiom above, if allowed, would make many of my methods simpler. Note that this use case has first-class support in languages, such as Scala, which consistently employ the Maybe monad:
final int i = calculateIndex().getOrElse(1);
I think this use case serves as a quite good motivation to allow that one special case where i
is definitely unassigned within the catch-block.
UPDATE
After some thought I am even more certain that this is just a weakness of the JLS model: if I declare the axiom "in the presented example, i
is definitely unassigned when control reaches the catch-block", it will not conflict with any other axiom or theorem. The compiler will not allow any reading of i
before it is assigned in the catch-block, so the fact whether i
has been assigned to or not cannot be observed.
i
may have been assigned if there are more statements following the assignment.Optional
.