如何在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 生日祝福语已婚朋友简短
18 上班祝福语简短10字