第7章课后作业

第3题,编写能长生ArrayIndexOutOfBoundsException异常的代码,并将其捕获,在控制台上输出异常信息

import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] arr = new int[3];
for (int i = 0; i < 4; i++) {
System.out.print("请输入"+(i+1)+"个数字:");
try {
arr[i]= in.nextInt();
} catch (Exception e) {
System.out.println("数组越界");
e.printStackTrace();
}
}
}

}

第4题:简述java异常体系结构

答:Thorwable类所有异常和错误的超类,有两个子类Error和Exception,分别表示错误和异常。 

    其中异常类Exception又分为运行时异常(RuntimeException)和非运行时异常

第5题修改第3题,使用log4j记录日志,在jbit.log文件中记录产生的异常信息

package test;
import org.apache.log4j.Logger;
public class Test {
static Logger logger = Logger.getLogger(Test.class.getName());
public static void main(String[] args) {
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
try {
arr[2] = 3;
} catch (Exception e) {
logger.error("数组越界");
}
}

}

控制台显示如下:


文件显示异常如下:


猜你喜欢

转载自blog.csdn.net/weixin_41880408/article/details/80229955