Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ExTestDrive.main(ExTestDrive.java:14):
程序代碼如下:
1 class MyEx extends Exception{} 2 3 public class ExTestDrive { 4 5 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 String test=args[0]; 9 try{ 10 System.out.println("t"); 11 doRisky(test); 12 System.out.println("o"); //如果沒有異常,才會執行下面這一句,如果捕獲異常,下面這一句直接跳過去了。 13 }catch(MyEx e){ 14 System.out.print("a"); 15 16 }finally{ 17 System.out.println("w"); 18 19 } 20 System.out.println("s"); 21 22 } 23 24 static void doRisky(String t) throws MyEx { 25 26 System.out.println("h"); 27 if("yes".equals(t)){ //看來t中會存儲main函數傳送給它的兩個值:yes or not.或許是控制台中傳遞的參數 28 throw new MyEx(); 29 30 } 31 System.out.print("r"); 32 // TODO Auto-generated method stub 33 34 } 35 36 }
1 你好,這個異常是初學者比較常見的異常。 2 ArrayIndexOutOfBoundsException:注意這個單詞,字面意思就是數組引用超出界限,也就是我們常說的越界問題。 3 4 比如,我們創建了一個數組 int a[] = new int[4] ; 5 那么數組a只能存放四個元素,而數組的下標是從0開始的,也就是說,a[3]就是最后一個元素。當你給a[4]賦值,或者使用a[4]的時候,就出現了ArrayIndexOutOfBoundsException異常。
1 你的args[]定義的是String數組 只給args[]數組聲明 沒給它分配空間 所以運行后出現的錯誤的意思是下標越界,代碼如下:、 2 public class b { 3 public static void main(String args[]){ 4 args=new String[3]; 5 System.out.println("hi!"+args[0]+" "+args[1]+" " +args[2]); 6 7 } 8 } 9 加args=new String[3];是個它分配空間你有args[0],args[1],args[2]三個所以是String[3],還可以給這數組賦值,如args[0]=new String("java")
添加了一句話:args=new String[3],為這個數組分配了空間。
1 class MyEx extends Exception{} 2 3 public class ExTestDrive { 4 5 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 args=new String[3]; 9 String test=args[0]; 10 try{ 11 System.out.print("t"); 12 doRisky(test); 13 System.out.print("o"); //如果沒有異常,才會執行下面這一句,如果捕獲異常,下面這一句直接跳過去了。 14 }catch(MyEx e){ 15 System.out.print("a"); 16 17 }finally{ 18 System.out.print("w"); 19 20 } 21 System.out.print("s"); 22 23 } 24 25 static void doRisky(String t) throws MyEx { 26 27 System.out.print("h"); 28 if("yes".equals(t)){ //看來t中會存儲main函數傳送給它的兩個值:yes or not.或許是控制台中傳遞的參數 29 throw new MyEx(); 30 31 } 32 System.out.print("r"); 33 // TODO Auto-generated method stub 34 35 }
運行結果就出來了:
throws。
說明控制台Console發送過來的消息是no.就是沒有拋出異常。
