gpt4 book ai didi

java - 什么是先到的 - finally 还是 catch block ?

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

考虑以下测试用例:

public class Main {

static int a = 0;

public static void main(String[] args) {
try {
test();
System.out.println("---");
test2();
}
catch(Exception e) {
System.out.println(a + ": outer catch");
a++;
}
}

public static void test()
{
try {
throw new Exception();
}
catch (Exception e) {
System.out.println(a + ": inner catch");
a++;
}
finally {
System.out.println(a + ": finally");
a++;
}
}

public static void test2() throws Exception
{
try {
throw new Exception();
}
finally {
System.out.println(a + ": finally");
a++;
}
}
}

有输出:

0: inner catch
1: finally
---
2: finally
3: outer catch

为什么在 test() 中 catch 发生在 finally 而在 test2() 中却相反?

最佳答案

关键点如下:

  • try-(catch)-finally 中 block ,finally对于那个特定的try block 最后执行
  • 你可以嵌套 try block 内的 block ,每个嵌套 try block 可以有自己的finally ,这将为那些个人 try 最后执行 block

是的,finally最后执行,但用于 try阻止它附加到。

所以给出以下代码段:

try {
try {
throw null;
} finally {
System.out.println("Finally (inner)");
}
} catch (Throwable e) {
System.out.println("Catch (outer)");
}

这会打印(as seen on ideone.com):

Finally (inner)
Catch (outer)

注意:

  • (inner)内, Finally是最后一个(无论 catch 是否成功)
  • Catch (outer)关注 Finally (inner) , 但那是因为 Finally (inner)嵌套在另一个try阻止 (outer)

同样,以下代码段:

    try {
try {
throw null;
} catch (Throwable e) {
System.out.println("Catch (inner)");
} finally {
System.out.println("Finally (inner)");
throw null;
}
} catch (Throwable e) {
System.out.println("Catch (outer)");
}

这会打印(as seen on ideone.com):

Catch (inner)
Finally (inner)
Catch (outer)

引用文献

相关问题

关于java - 什么是先到的 - finally 还是 catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3109353/

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