(1)编写能产生ArrayIndexOutOfBoundsException异常的代码,并将其捕获,在控制台上输出异常信息。
package com.homework.demo.test7; public class ArraysIndex { public static void main(String[] args) { int arr [] = new int [3]; //长度为3的整型数组 try { arr[3] = 2; //下标为3的元素赋值为2(数组越界) } catch (ArrayIndexOutOfBoundsException e) { //数组下标越界 // TODO: handle exception e.printStackTrace(); } } }
(2)修改第一题,使用log4j记录日志,在jbit.log文件中记录产生的异常信息。
package com.homework.demo.test7; import org.apache.log4j.Logger; public class ArraysIndexLog { private static Logger logger = Logger.getLogger(ArraysIndexLog.class.getName()); public static void main(String[] args) { // TODO Auto-generated method stub int arr [] = new int [3]; //长度为3的整型数组 try { arr[3] = 2; //下标为3的元素赋值为2(数组越界) } catch (ArrayIndexOutOfBoundsException e) { //数组下标越界 // TODO: handle exception logger.error(e.getMessage()); e.printStackTrace(); } } }