始める無料で始める

(再)スロー

メソッドが例外をスローした場合、呼び出し元のメソッドはその例外を処理しなければなりません。処理する方法は、try/catch で捕捉するか、再スローするかのいずれかです。この演習では、呼び出し元のメソッドがどのように例外を再スローするかを確認します。

この演習はコースの一部です

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();
		}
	}
}
コードを編集して実行