日期:2014-05-20  浏览次数:20863 次

一段代码
package doItMyself;

public class TestException {
static int[] myArray={0,1,2,3,4};

static void bob(){
try{
myArray[-1]=4;
}
catch(NullPointerException e){
System.out.println("caught a different exception");
}
}

public static void main(String[] args) {
try{
bob();
}
catch(Exception e){
System.out.println("caught exception in main()");
e.printStackTrace();
}
}

}
运行后输出信息如下:
caught exception in main()
java.lang.ArrayIndexOutOfBoundsException: -1
at doItMyself.TestException.bob(TestException.java:21)
at doItMyself.TestException.main(TestException.java:77)
哪位高手能解释以下么?


------解决方案--------------------
在bob函数里
只捕捉了NullPointerException 这个异常
而实际发生的异常是ArrayIndexOutOfBoundsException
所以它会被throw到外层
也就是main里
在main里捕捉了任何异常Exception
所以就是这样执行的
 System.out.println("caught exception in main()"); 
e.printStackTrace();