java 如何抛异常_如何在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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值