【问题标题】:Exception rethrowing in java [duplicate]java中的异常重新抛出[重复]
【发布时间】:2016-12-22 21:07:17
【问题描述】:

我在准备 OCA 时遇到了一个练习,我不明白为什么程序会打印:abce 3 而不是 abcde 3。这里的程序:

'public static void main(String[] args) {
        System.out.print("a");
         try{
            System.out.print("b");
             throw new IllegalArgumentException();
          }catch(IllegalArgumentException e){
              System.out.print("c");
              throw new RuntimeException("1");
          }catch(RuntimeException e) {
              System.out.print("d");
              throw new RuntimeException("2");
          }finally {
            System.out.print("e");
            throw new RuntimeException("3");
          }
        }'

任何解释为什么它忽略最后一个 catch 块将非常感激!

【问题讨论】:

  • Another problem is that the exception thrown in the last catch block is simply ignored or masked by the one thrown in the finally block。是的,这是一个问题,但它是 Java 内置的一个问题 :) 不要从 finally 块中抛出异常。

标签: java exception-handling


【解决方案1】:

finally总是try-catch 块之后执行,因此会打印eabc 是显而易见的,因为您在 try 中抛出异常并输入 IllegalArgumentException 的相应 catch 块。

但是,由于您抛出了一个新异常RuntimeException在 catch 块内,它会被抛出给您的方法的调用者。 catch处理try 块中抛出的异常,所有其他块都传递给您抛出异常的函数的调用者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多