Develop
[Spring Boot] IndexOutOfBoundsException 개선 작업
너드나무
2024. 7. 24. 18:23
반응형
서론
Spring Boot 환경에서 특정 API 호출 시 발생하는 IndexOutOfBoundsException 이슈를 정리해본다.
class java.lang.IndexOutOfBoundsException -
java.lang.IndexOutOfBoundsException:Index 0 out of bounds for length 0
해당 이슈는 리스트를 제어하는 로직에서
Index [0]에 위치하는 값을 찾을 수 없을 경우 발생할 수 있다.
IndexOutOfBoundsException (Java Platform SE 8 )
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
Problem Example
- IndexOutOfBoundsException은 컬렉션이나 배열의 인덱스가 유효 범위를 벗어날 때 발생하는 예외이다.
- 일반적으로 리스트의 특정 인덱스를 접근 시
- 해당 인덱스가 리스트의 크기보다 크거나 리스트가 비어 있는 경우에 발생한다.
- 해당 인덱스가 리스트의 크기보다 크거나 리스트가 비어 있는 경우에 발생한다.
- 리스트의 첫 번째 요소를 접근 시
- 리스트가 비어 있으면 IndexOutOfBoundsException이 발생합니다.
- 이는 프로덕션 환경에서 애플리케이션의 중단을 초래할 수 있기 때문에, 철저한 예외 처리가 필요하다.
return EventItem.builder()
.eventNo(eventNo)
.itemNo((items != null) ? items.get(0).getItemNo() : 0) // 예외 발생 가능
.build();
Solution Example
- 개선된 코드
- items가 null이 아니고, 비어 있지 않은 경우를 예외처리하여 첫 번째 요소 접근
- 이를 통해 IndexOutOfBoundsException을 방지
return EventItem.builder()
.eventNo(eventNo)
.itemNo((items != null && !items.isEmpty()) ? items.get(0).getitemNo() : 0) // 개선된 코드
.build();
728x90
반응형