面向对象第七章课后习题

1.编写能产生ArraylndexOutOfBoundsException 异常的代码,并将其捕获,在控制台上输出异常信息。
package kehouzuoye;

public class ArrExceptionTest2 {

	public static void main(String[] args) {
		// 使用判断数组下标越界的异常方法进行异常处理
		int [] arr = new int[5];
		try {
			arr[0]=1;
			arr[1]=2;
			arr[2]=3;
			arr[3]=4;
			arr[4]=5;
			arr[5]=6;//此位置出现数组越界
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("抱歉!数组下标已超过定义的数组长度。");
			e.printStackTrace();
		}
	}

}
2.修改第三题,使用log4j记录日志,在jbit.log文件中记录产生的异常信息。
package kehouzuoye;

import org.apache.log4j.Logger;

public class ArrExceptionTest {
	private static Logger logger = Logger.getLogger(ArrExceptionTest.class.getName());
	public static void main(String[] args) {
		// 使用判断数组下标越界的异常方法进行异常处理,并使用log4j记录日志
		int [] arr = new int[5];
		try {
			arr[0]=1;
			arr[1]=2;
			arr[2]=3;
			arr[3]=4;
			arr[4]=5;
			arr[5]=6;
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("抱歉!数组下标已超过定义的数组长度。");
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}

}

猜你喜欢

转载自blog.csdn.net/Duanhaifeng55/article/details/80230139
今日推荐