gpt4 book ai didi

java - 是否可以在 catch 中重新分配最终变量,即使分配是 try 中的最后一个操作?

转载 作者:IT老高 更新时间:2023-10-28 20:25:23 26 4
gpt4 key购买 nike

我很相信这里

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

i如果控制到达 catch-block,则不可能已经分配。然而,Java 编译器不同意并声称 the final local variable i may already have been assigned .

我在这里仍然缺少一些微妙之处,还是这只是 Java 语言规范用来识别潜在重新分配的模型的一个弱点?我主要担心的是 Thread.stop() ,这可能会导致“凭空”抛出异常,但我仍然不明白在赋值后如何抛出异常,这显然是 try block 中的最后一个操作。

如果允许,上面的成语将使我的许多方法更简单。请注意,此用例在 Scala 等语言中具有一流的支持,它始终使用 Maybe monad:

final int i = calculateIndex().getOrElse(1);

我认为这个用例是一个很好的动机,它允许 i 的一个特殊情况。在 catch block 中绝对未分配

更新

经过一番思考,我更加确定这只是 JLS 模型的一个弱点:如果我声明公理“在给出的示例中,i 在控制到达捕获 block 时肯定是未分配的”,它将不与任何其他公理或定理冲突。编译器不允许读取 i在它被分配到 catch-block 之前,所以事实上是否 i已分配或未分配无法观察。

最佳答案

JLS 狩猎:

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

第 16 章:

V is definitely unassigned before a catch block iff all of the following conditions hold:

V is definitely unassigned after the try block.
V is definitely unassigned before every return statement that belongs to the try block.
V is definitely unassigned after e in every statement of the form throw e that belongs to the try block.
V is definitely unassigned after every assert statement that occurs in the try block.
V is definitely unassigned before every break statement that belongs to the try block and whose break target contains (or is) the try statement.
V is definitely unassigned before every continue statement that belongs to the try block and whose continue target contains the try statement.

粗体字是我的。在 try block 之后,不清楚是否分配了 i

示例中的更多内容

final int i;
try {
i = foo();
bar();
}
catch(Exception e) { // e might come from bar
i = 1;
}

粗体文本是 only 条件,防止实际错误赋值 i=1 是非法的。因此,这足以证明“绝对未分配”的更精细条件是允许原始帖子中的代码所必需的。

如果规范被修改以替换此条件

V is definitely unassigned after the try block, if the catch block catches an unchecked exception.
V is definitely unassigned before the last statement capable of throwing an exception of a type caught by the catch block, if the catch block catches an unchecked exception.

那么我相信你的代码是合法的。 (根据我的特别分析。)

我为此提交了一个 JSR,我希望它会被忽略,但我很好奇这些是如何处理的。从技术上讲,传真号码是必填字段,我希望如果我在此处输入 +1-000-000-000,它不会造成太大的损失。

关于java - 是否可以在 catch 中重新分配最终变量,即使分配是 try 中的最后一个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17075061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com