如何在Java中抛出异常?
有时我们可能需要重新抛出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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短