繁体   English   中英

嵌套的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中。 执行try-finally和try-catch-finally

内部try块中的异常V的结果将取决于finally块的完成方式。 如果它正常完成,则try-finally将由于V而突然完成。如果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);
    }
  }
}

输出:

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区块的突然完成,第二个外部捕获没有看到“第二个例外”。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM