Java/Exception

[Exception] java.lang.ArrayIndexOutOfBoundsException

콩스프 2022. 11. 14. 17:05

 

✔ java.lang.ArrayIndexOfBoundsException

  • Unchecked Exception
  • 배열의 크기보다 크거나 음수인 index에 대한 요청(접근)이 있을 때 발생하는 에러
  • 컴파일 단계에서는 검사하지 않고 런타임(실행 도중)에 예외를 발생시킴

 


 

Scanner input = new Scanner(System.in);

int[] score = new int[3];

for(int i=0; i<=3; i++) {
    score[i]=input.nextInt();
}

 

🚨 Exception 발생 원인

  • i가 3일 때 Exception 발생
  • 배열의 크기가 3이므로 마지막 인덱스는 2
  • 인덱스의 범위를 넘어선 student[3]에 대한 요청으로 인해 Exception이 발생

 

 

🔍 Exception 해결방법

 

solution 01)

Scanner input = new Scanner(System.in);

int[] score = new int[3];

for(int i=0; i<score.length; i++) {
    score[i]=input.nextInt();
}
  • 인덱스 범위를 넘어가지 않게 하기 위해 조건문을 쓸 때 정수 리터럴 대신 length 필드를 사용