Could a final variable be reassigned in catch, even if assignment is last operation in try?

前端 未结 12 1173
粉色の甜心
粉色の甜心 2020-12-04 18:49

I am quite convinced that here

final int i;
try { i = calculateIndex(); }
catch (Exception e) { i = 1; }

i cannot possibly have

12条回答
  •  囚心锁ツ
    2020-12-04 19:25

    As per specs JLS hunting done by "djechlin", specs tells when is the variable definitely unassigned. So spec says that in those scenarios it is safe to allow the assignment.There can be scenarios other than the one mentioned in the specs in which case variable can still be unassigned and it will depend on compiler to make that intelligent decision if it can detect and allow an assignment.

    Spec in no way mentions in the scenario specified by you, that compiler should flag an error. So it depends on compiler implementation of spec if it is intelligent enough to detect such scenarios.

    Reference: Java Language Specification Definite Assignment section "16.2.15 try Statements"

提交回复
热议问题