Exception 객체
코드 조각이 여러 예외를 던지는 일은 흔합니다. 이를 처리하는 한 가지 방법은 모든 예외를 try-catch로 감싼 다음 exception 객체를 사용해 어떤 문제가 발생했는지 판단하고 Exception에서 정보를 출력해 디버깅하는 것입니다.
이번에는 SplitTheBill 애플리케이션을 다시 수정하여 일반적인 Exception을 catch하고, Exception 객체의 데이터를 사용해 문제의 원인을 파악해 보겠습니다. Exception 객체에는 문제로 이어지는 메서드 호출 추적 등 유용한 정보가 많이 담겨 있어요.
이 연습은 강의의 일부입니다
Java의 데이터 타입과 예외
연습 안내
- catch 블록에서
catch (Exception e)를 사용해 모든Exception을 포착하세요. - catch 블록에서
Exception객체 참조(e)와getClass()메서드를 사용하여 포착한 예외의 타입(클래스)을 표시하세요. Exception객체 참조(e)와getMessage()메서드를 사용하여 예외 메시지를 출력하세요.Exception객체 참조(e)와printStackTrace()메서드를 사용해 출력 스트림으로 "stack trace"를 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
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
____.____();
}
}
}