如何在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 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短