嵌套的try异常会被外部catch块捕获吗?

5
我有类似这样的内容。
try{   
  try{ . .a method call throwing a exception..} 
  finally { ...} 
} catch()...

方法调用抛出的异常类型和外部catch块的类型参数相同。

嵌套的try块抛出的异常是否会被外层的catch块捕获?


6
未捕获的异常将一直往上冒,直到遇到匹配的catch语句或者达到顶级作用域并导致整个应用程序崩溃。 - Marc B
@MarcB 不一定。如果内部的 finally 块突然完成,它完成的原因将会冒泡上来,而不是原始异常。 - Patricia Shanahan
1个回答

15

相关规则请参见Java语言规范,14.20.2. try-finally和try-catch-finally的执行

在内部try块中发生异常V,取决于finally块的完成方式。如果正常完成,则try-finally由于V而突然终止。如果由于某种原因R而使finally块突然终止,则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块的一个突然完成,第二个外部catch未能看到"Second exception"。

尽量减小finally块突然完成的风险。在其中处理任何异常,以使其正常完成,除非它们对整个程序将产生致命影响。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接