首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

一段代码解决方案

2012-01-30 
一段代码package doItMyselfpublic class TestException {static int[] myArray{0,1,2,3,4}static void

一段代码
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(); 

热点排行
Bad Request.