시작하기무료로 시작하기

예외 (재)던지기

메서드가 예외를 던지면, 그 메서드를 호출한 쪽에서 해당 예외를 처리해야 해요. 처리 방식은 try/catch로 직접 처리하거나, 예외를 다시 던지는(rethrow) 것이에요. 이 연습 문제에서는 호출하는 메서드가 예외를 다시 던지는 방법을 살펴봅니다.

이 연습은 강의의 일부입니다

Java의 데이터 타입과 예외

강의 보기

연습 안내

  • dineOut() 메서드를 인원 9로 호출해 Exception이 발생하도록 하세요.
  • dineOut() 메서드가 예외를 처리하지 않으므로, Exception을 다시 던지세요.
  • splitBill() 메서드도 예외를 처리하지 않으므로, Exception을 던지세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

public class RethrowingExample {

	public static void main(String[] args) {
		try {
			// Trigger the exception by calling dineOut with 9 people
			dineOut(____, 50.00);
		} catch (Exception e) {
			System.out.println("Atempting to divide bill with too many diners");
		}
	}

	// Rethrow the Exception
	public static void dineOut(int people, double bill) ____ ____ {
		double each = splitBill(bill, people);
		System.out.println("Bill for each person: " + each);
	}

	// Throw the Exception
	public static double splitBill(double bill, int people) ____ ____ {
		if (people < 3) {
			return bill / people;
		} else {
			throw new Exception();
		}
	}
}
코드 편집 및 실행