Throws
메서드는 예외가 던져질 때 try-catch로 직접 처리할 수도 있고, 예외를 호출자에게 다시 던질 수도 있습니다(책임을 넘기는 방식). 이번 연습에서는 try/catch로 처리하는 대신 예외를 던지는 방법을 살펴봅니다.
이 연습은 강의의 일부입니다
Java의 데이터 타입과 예외
연습 안내
getScore(3)을 호출하고 그 값을 출력하는 코드 주변에 try 블록을 추가하세요.getScore()메서드에서 발생하는ArrayIndexOutOfBoundsException을 처리하는 catch 블록을 추가하세요.- 예외를 try/catch로 처리하는 대신,
getScore(int)가ArrayIndexOutOfBoundsException을 던지도록 하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
package exceptions;
public class ThrowingExample {
public static int[] scores = { 75, 97, 83 };
public static void main(String[] args) {
// Add a try block
____ {
int lastScore = getScore(3);
System.out.println("Last score:" + lastScore);
// Catch the exception thrown by getScore(int)
} ____ (____ e) {
System.out.println("Tried to access non-existent score");
}
}
// Throw ArrayIndexOutOfBoundsException
public static int getScore(int index) ____ ____ {
return scores[index];
}
}