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

cur*_*ous 4 java exception-handling

我有类似的东西

try{   
  try{ . .a method call throwing a exception..} 
  finally { ...} 
} catch()...
Run Code Online (Sandbox Code Playgroud)

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

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

Pat*_*han 12

相关规则在Java语言规范14.20.2中.执行try-finally和try-catch-finally

V内部try块中的异常结果将取决于finally块的完成方式.如果正常完成,try-finally如果将突然完成,由于五finally块突然因为某种原因完成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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

由于第二finally块突然完成,第二个外部捕获没有看到"第二个例外" .

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