1.编写能产生ArrayIndexOutOfBoundsException异常的代码,并将其捕获,在控制台输出异常信息。
package come.diqizhang.dome; /** * * @author 数组类 * */ public class ArrayException { public static void main(String[] args) { int[] score = new int[4]; //创建数组 try { score[4] = 5; }catch (ArrayIndexOutOfBoundsException e) { //判断是否数组越界 // TODO: handle exception System.err.println("数组越界!"); e.getMessage(); e.printStackTrace(); } } }
2.修改第一题,使用log4j记录日志,在jbit.log文件记录产生的异常信息。
package come.diqizhang.dome; import org.apache.log4j.Logger; /** * * @author Lenovo * */ public class ArrayException1 { private static Logger logger =Logger.getLogger(ArrayException1.class.getName()); public static void main(String[] args) { // 使用判断数组下标越界的异常方法进行异常处理,并使用log4j记录日志 int[] score = new int[4]; try { score[4] = 5; }catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception System.err.println("数组越界!"); logger.error(e.getMessage()); e.printStackTrace(); } } }