ArrayIndexOutOfBoundsException対策
 
ArrayIndexOutOfBoundsExceptionは、配列として確保された領域を
超えた場所アクセスした場合に発生します。
 
 
  
samples/exception/index/ArrayIndexOutOfBoundsExceptionTest.java - Eclipse SDK
 |  
package samples.exception.index; 
 
public class ArrayIndexOutOfBoundsExceptionTest { 
  public static void main(String[] args) { 
    int[] intArray = { 1, 2, 3 }; 
    try { 
      System.out.println(intArray[0]); 
      System.out.println(intArray[1]); 
      System.out.println(intArray[2]); 
      System.out.println(intArray[3]); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 
}
 | 
 
 
 
 |   
上記の例では、intArrayという変数に3つの要素を持つ配列を作成しています。
Java言語では、配列の添え字は0から始まるため、この場合は
[0], [1], [2] の3つだけが、有効な添え字となります。
 
ここでは、わざと、存在しない 4番目(intArray[3])にアクセスして、
ArrayIndexOutOfBoundsExceptionが発生することを確認しています。
 
 
  
コマンド プロンプト
 |  
 
C:\JavaMaster\bin>java -cp . samples.exception.index.ArrayIndexOutOfBoundsExceptionTest  
1 
2 
3 
java.lang.ArrayIndexOutOfBoundsException: 3 
    at samples.exception.index.ArrayIndexOutOfBoundsExceptionTest.main(ArrayIndexOutOfBoundsExceptionTest.java:10) 
 
 |   
通常は、配列のすべての内容に頭から順番にアクセスするには、
次のようにコーディングします。
 
 
  
samples/exception/index/ArrayIndexOutOfBoundsExceptionTest2.java - Eclipse SDK
 |  
package samples.exception.index; 
 
public class ArrayIndexOutOfBoundsExceptionTest2 { 
  public static void main(String[] args) { 
    int[] intArray = { 1, 2, 3 }; 
    for (int i = 0; i < intArray.length; i++) { 
      System.out.println(intArray[i]); 
    } 
  } 
}
 | 
 
 
 
 |   
  
コマンド プロンプト
 |  
 
C:\JavaMaster\bin>java -cp . samples.exception.index.ArrayIndexOutOfBoundsExceptionTest2  
1 
2 
3 
 
 |   
 
         
         
         
         
         
         
         
 
 
  |