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

will the nested try exception be caught by outer catch block

我有这样的东西

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

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

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

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

内部 try 块中异常 V 的结果将取决于 finally 块的完成方式。如果它正常完成,try-finally 将由于 V 突然完成。如果 finally 块由于某种原因突然完成 R 然后 try-finally 由于 [=17 而突然完成=],并且 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 块的突然完成,第二个外部捕获没有看到 "Second exception"。

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