这道题不交,wdnmd
public class Test6_1_zxj {
// (一) 常见异常的捕获
//
// (1) 编写一个程序,分别生成ArrayIndexOutOfBoundsException类型和ArithmeticException类型的异常。
//
// (2) 改写程序,对ArrayIndexOutOfBoundsException和ArithmeticException类型异常进行捕获。
//
// 思考:能否同时抛出ArrayIndexOutOfBoundsException类型和ArithmeticException类型的异常?为什么?
//答:不能,程序每次只能捕获一个异常,可以把catch全都去掉,会优先报算数异常,捕获算数异常之后,再运行,会报越界异常
public static void main(String args[])
{
int[] a={1,2,3,4};
int num=0;
for(int i=0;i<5;i++)
{
try {
num=a[i]/i;
}
catch(ArithmeticException e)
{
System.out.println("算术异常");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("数组越界异常");
}
System.out.println(num);
}
}
}

数组越界异常的输出的1,是num的值
本文深入探讨了Java中常见的异常类型ArrayIndexOutOfBoundsException和ArithmeticException,通过实例演示了如何生成及捕获这两种异常,并解释了为何程序无法同时抛出并捕获多个异常。
2366





