문제:
ExceptionExam클래스의 get50thItem메소드에서는 매개변수로 받은 array의 50번째 값을 return합니다. 만약 array의 크기가 50보다 작을 경우에는 ArrayIndexOutOfBoundsException이라는 예외가 발생하는데요. get50thItem이 ArrayIndexOutOfBoundsException를 throw하도록 정의해 보세요.
public class ExceptionExam {
public int get50thItem(int[] array) throws ArrayIndexOutOfBoundsException {
return array[49];
}
}
public class ExamExam {
public static void main(String[]args){
ExceptionExam ex = new ExceptionExam();
int[] array = new int[100];
try {
System.out.println(ex.get50thItem(array));
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("문제 발생" + e.toString());
}
}
}
정말 쉬운 문제였는데 문제를 제대로 이해하지 않았던 것 같아서 실수를 되새김질 하기 위해 리뷰를 한다.
array는 50번째 값을 리턴하고 이보다 작을 경우에는 예외 발생
나는 여기서 array크기가 나와있지 않은데?
이런 바보 같은 생각을 했었는데, 그냥 내가 array를 선언하고
try문에서 return array[49] 같은 코드가 아닌
throws의 본질인 예외를 호출한 메소드에서 처리하는 코드로 작성했어야 했음을 알게 되었다.
'코딩테스트 연습(with java) > 프로그래머스' 카테고리의 다른 글
프로그래머스 연습문제<문자열을 정수로 바꾸기 > (0) | 2022.05.14 |
---|---|
프로그래머스 연습문제<없는 숫자 더하기> (0) | 2022.05.14 |
프로그래머스 연습문제<핸드폰 번호 가리기> (0) | 2022.05.11 |
프로그래머스 연습문제<짝수와 홀수> (0) | 2022.05.11 |
프로그래머스 연습문제 <약수의 합> (0) | 2022.05.08 |