throws异常

博客介绍了在Java程序中,若要自行抛出异常,需使用throw语句。该语句可单独使用,它抛出的是异常实例,且每次只能抛出一个。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果需要在程序中自行抛出异常,则应使用throw语句,throw语句可以单独使用,
throw语句抛出的不是异常类,而是一个异常实例,而且每次只能抛出一个异常实例。
Main:

public static void main(String[] args) throws Exception {
// 数组索引越界 ArrayIndexOutOfBoundsException
// String[] strs = { "1" };
// 算术异常(除零) ArithmeticException
String[] strs = { "18", "0" };
intDivide(strs);
}
public static void intDivide(String[] strs) throws Exception {
	if (strs.length<2) {
//自行抛出 Exception异常
//该代码必须处于try块里,或处于带 throws声明的方法中
	throw new Exception("参数个数不够");
}
	if (strs[1]!=null && strs[1].equals("0")) {
//自行抛出 RuntimeException异常,既可以显式捕获该异常
//也可完全不理会该异常,把该异常交给该方法调用者处理
	throw new RuntimeException("除数不能为0");
}
	int a = Integer.parseInt(strs[0]);
	int b = Integer.parseInt(strs[1]);
	int c = a / b;
	System.out.println("结果是 :" + c);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值