IndexOutOfBounds Exception 처리

KooYm·2021년 11월 30일
0

이 때까지 List, ArrayList, Array 등을 사용하여 for문으로 탐색할 때나 다음 요소가 있는지 확인을 안하고 사용하는 경우에
'IndexOutOfbounds Exception'으로 앱이 튕기는 현상이 잦았다.

이걸 하나하나 찾아서 고치기도 애매하고 어떻게 처리를 해야할까 싶은 와중
그냥 try catch 문으로 IndexOutOfBounds Exception 만 처리를 하면 되었다.

 if (storeDTO.isAdItem() && !recommendList.get(recommendList.indexOf(storeDTO) + 1).isAdItem()) {
                    binding.divider.setVisibility(View.VISIBLE);
 }

이게 원래 쓰이던 코드인데, recommendList.indexOf(storeDTO) +1 부분에서 만약 다음 요소가 존재하지 않을 때 문제가 생긴 것이다.
이를 위해서 try catch 문을 사용하면

try{
	if (storeDTO.isAdItem() &&!recommendList.get(recommendList.indexOf(storeDTO) + 1).isAdItem()) {
                binding.divider.setVisibility(View.VISIBLE);
        }
}catch (IndexOutOfBoundsException e){
	if(storeDTO.isAdItem())
                binding.divider.setVisibility(View.VISIBLE);
}

로 간단하게 해결할 수 있다.

물론 다른 부분도 다 생각해야 하지만, 임시방편으로 해결하는 방법이다.

profile
안드로이드 끄적끄적

0개의 댓글