如何在 Java 中重新抛出异常?
有时候我们需要在 Java 中重新抛出异常。如果一个 catch 代码块无法处理其捕捉到的特定异常,我们可以重新抛出该异常。rethrow 表达式会导致最初抛出的对象被重新抛出。
由于异常已经在 rethrow 表达式出现的范围内被捕获,因此它被重新抛出到下一个包含的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP