嵌套的try异常是否会被外部catch块捕获

时间:2015-06-01 14:10:29

标签: java exception-handling

我有类似的东西

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

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

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

1 个答案:

答案 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阻止的风险。处理其中的任何异常,以便它能够正常完成,除非它们对整个程序来说是致命的。