정해진 배열의 크기보다 크거나 음수 index에 대한 요청이 있으면 ArrayIndexOutOfBoundsException이 발생한다.
int[] arr = new int[5] // arr의 범위는 arr[0] ~ arr[4]로 총 5개의 인덱스를 생성
arr[5] = 5; // arr[5]는 존재하지 않기 때문에 예외 발생!
// 결과
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at ArrTest.main(ArrTest.java:7) // Index 5는 배열의 length의 범위를 벗어났다는 뜻
for(int i = 0; i < arr.length; i++) { ... } // 배열의 범위만큼만 반복
int i = 0;
while(i < arr.length) { // 배열의 범위만큼만 반복
...
i++;
}
for(int i : arr) { ... } // 배열의 범위만큼만 반복
try { // 예외가 발생할 것 같은 코드 작성
int[] arr = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i;
}
// catch([발생할 것 같은 예외] [예외 변수 이름]) { 예외 발생 시 실행할 코드 }
} catch (ArrayIndexOutOfBoundsException e) { // ArrayIndexOutOfBoundsException가 발생하면 ArrayIndexOutOfBoundsException 출력해줘
System.out.println(e);
}