Exception 对象
一段代码抛出多个异常并不罕见。处理这种情况的一种方式是使用 try-catch 捕获所有异常,然后利用 exception 对象来判断发生了什么问题,并从 Exception 中输出信息以便调试。
在这里,您将再次修改 SplitTheBill 应用,catch 一个通用的 Exception,并使用 Exception 对象中的数据来理解问题的原因。Exception 对象包含大量有用信息,包括导致问题的方法调用轨迹。
本练习是课程的一部分
Java 的数据类型与异常
练习说明
- 在 catch 块中,使用
catch (Exception e)捕获任意Exception。 - 在
catch块中,使用Exception对象引用(e)与getClass()方法来显示捕获到的异常类型(类)。 - 使用
Exception对象引用(e)与getMessage()方法打印异常消息。 - 使用
Exception对象引用(e)与printStackTrace()方法将"堆栈跟踪"打印到输出流。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class SplitTheBill {
public static void main(String[] args) {
BigDecimal bill = new BigDecimal(125.50);
computeEachBill(bill, 5);
computeEachBill(bill, 0);
}
public static void computeEachBill(BigDecimal bill, int people) {
try {
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// Catch any exception
} catch (____ ____) {
System.out.println("You didn't provide a positive number of people to split the bill among.");
// Print the type (class) of exception
System.out.println("Type of exception: " + ____.____());
// Print the exception message
System.out.println(____.____());
// Print the stack trace
____.____();
}
}
}