Note that there are some explanatory texts on larger screens.

plurals
  1. POCould a final variable be reassigned in catch, even if assignment is last operation in try?
    primarykey
    data
    text
    <p>I am quite convinced that here</p> <pre><code>final int i; try { i = calculateIndex(); } catch (Exception e) { i = 1; } </code></pre> <p><code>i</code> cannot possibly have already been assigned if control reaches the catch-block. However, Java compiler disagrees and claims <code>the final local variable i may already have been assigned</code>.</p> <p>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 <code>Thread.stop()</code>, 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.</p> <p>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 <em>Maybe</em> monad:</p> <pre><code>final int i = calculateIndex().getOrElse(1); </code></pre> <p>I think this use case serves as a quite good motivation to allow that one special case where <code>i</code> is <em>definitely unassigned</em> within the catch-block.</p> <h2>UPDATE</h2> <p>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, <code>i</code> 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 <code>i</code> before it is assigned in the catch-block, so the fact whether <code>i</code> has been assigned to or not cannot be observed.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload