开始使用免费开始使用

(重新)抛出异常

当一个方法抛出异常时,调用它的方法必须处理该异常。要处理它,可以使用 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();
		}
	}
}
编辑并运行代码