如何在 Java 中重新抛出异常?\

javaobject oriented programmingprogramming

有时我们可能需要在 Java 中重新抛出异常。如果 catch 块无法处理它捕获的特定异常,我们可以重新抛出该异常。重新抛出表达式会导致最初抛出的对象被重新抛出。

由于异常已经在重新抛出表达式发生的范围内被捕获,因此它会被重新抛出到下一个封闭的 try 块。因此,它无法由重新抛出表达式发生的范围内的 catch 块处理。封闭 try 块的任何 catch 块都有机会捕获异常。

语法

catch(Exception e) {
   System.out.println("An exception was thrown");
   throw e;
}

示例

public class RethrowException {
   public static void test1() throws Exception {
      System.out.println("The Exception in test1() method");
      throw new Exception("thrown from test1() method");
   }
   public static void test2() throws Throwable {
      try {
         test1();
      } catch(Exception e) {
         System.out.println("Inside test2() method");
         throw e;
      }
   }
   public static void main(String[] args) throws Throwable {
      try {
         test2();
      } catch(Exception e) {
         System.out.println("Caught in main");
      }
   }
}

输出

The Exception in test1() method
Inside test2() method
Caught in main

相关文章