Finally
이번에는 이전 연습 문제의 SplitTheBill 계산기를 수정해서, Exception이 발생해 catch에 걸리더라도 finally를 사용해 개인별 계산 금액을 출력하도록 하세요.
이 연습은 강의의 일부입니다
Java의 데이터 타입과 예외
연습 안내
try를 추가하고try코드 블록을 시작하세요.catch코드 블록을 마무리하고finally코드 블록을 추가하세요.finally코드 블록을 마무리하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
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
____
}
}