gpt4 book ai didi

java - try block 中的可达 break 语句

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:57 24 4
gpt4 key购买 nike

JLS 14.21 给出了一些Unreachable statements 的描述。特别是它说:

A reachable break statement exits a statement if, within the break target, either there are no try statements whose try blocks contain the break statement, or there are try statements whose try blocks contain the break statement and all finally clauses of those try statements can complete normally.

我正试图通过示例发现该规则。我编写了以下简单的测试程序:

public static void main(String[] args) throws java.lang.Exception {
while (true) {
try { //Try statement which contains a break statement.
break;
}
finally { //Finally always complete abruptly
throw new Exception(); //because of throwing an exception.
}

try { //Compile-time error: Unreachable statement
}
finally { //That finally doesn't contain any instruction.
//It always complete normally.
}
}
}

除了在以下示例中抛出异常外,我没有发现该行为有什么奇怪之处:<​​/p>

public static void main(String[] args) throws java.lang.Exception {
while (true) {
try {
break;
}
finally {
throw new Exception(); //Run-time error due to throwing an exception.
}
}
}

该规则的具体内容是什么?

最佳答案

如果控制流遇到 try/finally block 的 try 部分,则 finally 部分将总是运行。 (这对于立即清理资源非常有用,因为依赖垃圾收集器是不明智的。)

唯一的异常(exception)是 try 部分中的调用关闭了 JVM。例如 System.exit(...)

在您的情况下,程序流永远无法到达第二个 try,因此第二个 finally 也无法到达。

关于java - try block 中的可达 break 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26355232/

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