我很困惑为什么 finally
在 break
/continue
之后被执行(版本:Java 8 update 5)
testTryFinally();
function testTryFinally()
{
try
{
print("Try 1");
for(var i = 0; i < 2; i++)
{
break;
}
print("Try 2");
}
finally
{
print("Finally executed");
}
}
执行:
.../tmp>jjs 测试.js
带break
的输出:
Try 1
Finally executed
Try 2
Finally executed
用 continue
代替 break
输出
Try 1
Finally executed
Finally executed
Try 2
Finally executed
我尝试在浏览器中执行相同的代码(将 print()
替换为 console.log()
Firebug 中的输出符合预期
Try 1
Try 2
Finally executed
最佳答案
找到相关说法here :
. . . While it's true
finally
will always be executed if defined, certain statements insidetry
such ascontinue
,break
,return
, or when an error has occurred and there is no catch clause will all causefinally
to be executed immediately thereafter . . .
但我没有看到这在 Firefox 中发生(可能有充分的理由)
关于javascript - break 和 continue 语句导致 Nashorn 中的 finally block 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719066/