티스토리 뷰


java.lang.IndexOutOfBoundsException 에러 해결 방법

오늘은 아주 빈번하게 만나게 되는 IndexOutOfBoundsException, ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException 예외에 대해서 알아보자. 이 세가지는 비스무리하기 때문에 한꺼번에 알아보자.

 

API 문서를 보면 원인이 아주 쉽게 나온다.

 

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.Applications can subclass this class to indicate similar exceptions.

배열, 문자열 또는 벡터와 같은 일종의 인덱스가 범위를 벗어 났음을 나타냅니다. 응용 프로그램은이 클래스를 서브 클래싱하여 유사한 예외를 나타낼 수 있습니다.

배열, 문자열, 벡터(리스트와 같은 자료형)에서 인덱스 범위를 벗어나는 경우에 발생한단다. 그러면 위 세가지 유형을 각각 발생시키는 코드를 만들어보자.

 

package test;

import java.util.ArrayList;
import java.util.List;

public class test_IndexOutOfBoundsException {
	public static void main(String[] args) {
		
		// 1. java.lang.ArrayIndexOutOfBoundsException
		try {			
			int[] arrInt = new int[0];
			System.out.println(arrInt[0]);
		} catch (Exception e) {
			System.out.println("1. ArrayIndexOutOfBoundsException 에러 : ");
			e.printStackTrace(System.out);
			System.out.println("==============================================");
		}
		
		// 2. java.lang.StringIndexOutOfBoundsException
		try {
			String str = "hello";
			System.out.println(str.substring(11));
		} catch (Exception e) {
			System.out.println("2. StringIndexOutOfBoundsException 에러 : ");
			e.printStackTrace(System.out);
			System.out.println("==============================================");
		}
		
		// 3. java.lang.IndexOutOfBoundsException
		try {
			List list = new ArrayList();
			System.out.println(list.get(0));			
		} catch (Exception e) {
			System.out.println("3. IndexOutOfBoundsException 에러 : ");
			e.printStackTrace(System.out);
			System.out.println("==============================================");
		}
	}	
}

 

ㄹㄹㄹ모두 정해진 길이를 벗어난 경우 발생한다. 길이를 벗어나지 않게끔 호출하기 위해 먼저 길이를 체크하고 접근하는 방식을 쓰거나 업무적인 확인이 필요한 경우가 많다. 무조건 길이를 체크하고 접근한다는게 능사가 아니다. 때로는 돌아가게 만들기 위한 예외 처리가 더 큰 문제를 만들게 된다.

 

좀 더 풀어서 쇼핑몰 주문을 생각해보자. A라는 상품코드를 주문한 다음에 A에 맞는 옵션 별 가격 리스트를 가져와 선택하는 식으로 만들었다고 가정해보자. 가격 리스트를 가져오지 못하는 경우를 예외처리하여 0원으로 결제되어버리면 큰일이다. ( 물론 이렇게 간단하게 넘어가진 않겠지만 모르는 일이다. ) 

 

해서 해결방법은 1. if를 통해 먼저 길이를 검사하고 접근하지 않게끔 처리하거나, 2. 앞서서 배열, 리스트, 문자열의 길이가 충분하게끔 선결 조건을 만족시켜주게끔 해야한다. 3. 아니면 아예 프로그램 코드 자체를 바꾸던가...

 

https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html

 

IndexOutOfBoundsException (Java Platform SE 7 )

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range. Applications can subclass this class to indicate similar exceptions.

docs.oracle.com


댓글
최근에 올라온 글
최근에 달린 댓글