Get startedGet started for free

(Re)Throwing

When a method throws an exception, the calling method must handle that exception. To handle it, it can try/catch it or throw the exception again. In this exercise, you will see how a calling method rethrows an exception.

This exercise is part of the course

Data Types and Exceptions in Java

View Course

Exercise instructions

  • Call the dineOut() method with 9 people triggering the Exception.
  • Since the dineOut() method is not handling the exception, rethrow the Exception.
  • Since the splitBill() method is not handling the exception, throw the Exception.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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();
		}
	}
}
Edit and Run Code