1 请指出下列Java代码的错误
public class Test {
public void test(){
try{
System.out.println(“try”);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(“catch 1”);
}catch(Exception e){
System.out.println(“catch 2”);
}catch(NullPointerException e){
System.out.println(“catch 3”);
}
}
}
答:使用多重 catch 语句时 catch中的Exeception e应该放在除此之外所有的异常类型后面
2
答:运行结果:23 4 原因 :进入if语句—〉抛出异常——〉进入catch—〉输出2----〉进入finally—>输出3—〉执行剩余代码—〉输出4
3编写能产生ArrayIndexOutOfBoundsException 异常的代码,并将其捕获,在控制台输出异常信息
public class Test2 {
public static void main(String[] args){
int[] a = {1,2,3};
for (int i = 0; i < 5; i++) {
try {
System.out.println(a[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
}
}
}
4简述Java异常体系结构
答1、Error与Exception
Error是程序无法处理的错误,比如OutOfMemoryError、ThreadDeath等。这些异常发生时,
Java虚拟机(JVM)一般会选择线程终止。
Exception是程序本身可以处理的异常,这种异常分两大类运行时异常和非运行时异常。
程序中应当尽可能去处理这些异常。