Finally
Bây giờ, hãy chỉnh sửa máy tính SplitTheBill ở bài trước để dùng finally nhằm in số tiền mỗi người phải trả, ngay cả khi có Exception bị bắt.
Bài tập này là một phần của khóa học
Kiểu dữ liệu và Exceptions trong Java
Hướng dẫn bài tập
- Thêm
tryvà phần bắt đầu của khối mãtry. - Hoàn tất khối mã
catchvà thêm một khối mãfinally. - Hoàn tất khối mã
finally.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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) {
BigDecimal individualBill = new BigDecimal(0);
BigDecimal numPeople = new BigDecimal(people);
// Add a try and the beginning of the try code block
____ ____
individualBill = bill.divide(numPeople);
} catch (ArithmeticException e) {
System.out.println("You didn't provide a positive number of people to split the bill among. Assuming 2 people.");
numPeople = new BigDecimal(2);
individualBill = bill.divide(numPeople);
// End the catch code block and add a finally block
____ ____ ____
System.out.println("Bill for each of " + numPeople + " persons is: " + individualBill);
// End the finally block
____
}
}