早教吧 育儿知识 作业答案 考试题库 百科 知识分享

编写Exceptiontest程序,具有下面功能:编写Exceptiontest程序,具有下面功能:a)从命令行接收两个数,计算两数相除,捕获除数为零的异常。b)抛出一个ArrayIndexOutOfBoundsException异常,并捕

题目详情
编写Exception_test程序,具有下面功能:
编写Exception_test程序,具有下面功能:
a) 从命令行接收两个数,计算两数相除,捕获除数为零的异常。
b) 抛出一个ArrayIndexOutOfBoundsException异常,并捕获处理
▼优质解答
答案和解析
public class Exception_test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
try {
System.out.println(compute(num1, num2));
throw new ArrayIndexOutOfBoundsException(-1);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
} finally {
scanner.close();
}
}

public static double compute(int num1, int num2) {
double result;
try {
result = num1 / num2;
} catch (ArithmeticException e) {
throw new ArithmeticException("除数不能为0");
}
return result;
}
}