我有类似的东西
try{
try{ . .a method call throwing a exception..}
finally { ...}
} catch()...
方法调用和外部catch(类型参数)抛出的异常类型相同。
嵌套的try异常是否会被外部catch块捕获?
答案 0 :(得分:12)
相关规则在Java语言规范14.20.2. Execution of try-finally and try-catch-finally
中内部V
块中的异常try
的结果将取决于finally
块的完成方式。如果它正常完成,try-finally
将因V而突然完成。如果finally
块由于某种原因R
突然完成,则try-finally
由于{{1}突然完成},并且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
阻止的风险。处理其中的任何异常,以便它能够正常完成,除非它们对整个程序来说是致命的。