编写能产生ArrayIndexOutOfException异常的代码并将其捕获在控制台上输出异常信息,如何解决?
问题描述:
编写能产生ArrayIndexOutOfException异常的代码并将其捕获在控制台上输出异常信息
答
编写try-catch语句,在语句中创建数组并访问数组范围以外的下标,在catch中使用printerr打印异常
答
public class Demo {
public static void main(String[] args) {
try{
int []nums={1,2,3};
System.out.println(nums[3]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("数组越界异常");
}
}
}
答
public static void main(String[] args) {
try{
List<Integer> list = new ArrayList<>();
Integer[] objects = list.toArray(new Integer[list.size()]);
System.out.println(objects[0]);
}catch (Exception e){
System.out.println("数组越界异常: " + e.getMessage());
e.printStackTrace();
}
}