gpt4 book ai didi

java - 嵌套的 try 异常是否会被外部 catch block 捕获

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:29 32 4
gpt4 key购买 nike

我有这样的东西

try{   
try{ . .a method call throwing a exception..}
finally { ...}
} catch()...

方法调用和外层catch(类型参数)抛出的异常类型相同。

嵌套的try异常会被外层的catch block 捕获吗?

最佳答案

相关规则在Java语言规范中,14.20.2. Execution of try-finally and try-catch-finally

内部 try block 中异常 V 的结果将取决于 finally block 如何完成。如果它正常完成,try-finally 将由于 V 而突然完成。如果 finally block 由于某种原因 R 突然完成,则 try-finally 由于 R 而突然完成,V 被丢弃。

这是一个演示这个的程序:

public class Test {
public static void main(String[] args) {
try {
try {
throw new Exception("First exception");
} finally {
System.out.println("Normal completion finally block");
}
} catch (Exception e) {
System.out.println("In first outer catch, catching " + e);
}
try {
try {
throw new Exception("Second exception");
} finally {
System.out.println("finally block with exception");
throw new Exception("Third exception");
}
} catch (Exception e) {
System.out.println("In second outer catch, catching " + e);
}
}
}

输出:

Normal completion finally block
In first outer catch, catching java.lang.Exception: First exception
finally block with exception
In second outer catch, catching java.lang.Exception: Third exception

由于第二个 finally block 的突然完成,第二个外部捕获没有看到“第二个异常”。

尽量减少 finally block 突然完成的风险。处理其中的任何异常,以便它正常完成,除非它们对整个程序来说是致命的。

关于java - 嵌套的 try 异常是否会被外部 catch block 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575754/

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