如何在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 新生祝福语简短8字
11 老师出国祝福语大全简短
12 今日祝福语简短10字
13 顾客简短祝福语大全集
14 孙子结婚祝福语大全简短
15 婆婆生日祝福语短语简短
16 比较简短浪漫的祝福语
17 Q穷人结婚祝福语简短
18 公司五一祝福语简短最新