Java---------------throw异常

如果需要在程序中自行抛出异常,则应使用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);
}


猜你喜欢

转载自blog.csdn.net/weixin_44540416/article/details/89842940