시작하기무료로 시작하기

Try-catch

0으로 나누는 연산처럼 발생할 수 있는 산술 예외를 포착하고, 메시지를 표시해 처리하세요. 또한 미리 로드된 BigDecimal 패키지의 활용 예도 더 살펴보게 됩니다.

이 연습은 강의의 일부입니다

Java의 데이터 타입과 예외

강의 보기

연습 안내

  • trytry 코드 블록의 시작을 추가하세요.
  • (ArithmeticException e)ArithmeticException을 포착하고 catch 코드 블록을 시작하세요.
  • catch 코드 블록을 마무리하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

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) {
		// Add a try and the beginning of the try code block
		____ ____
			BigDecimal numPeople = new BigDecimal(people);
			BigDecimal individualBill = bill.divide(numPeople);
			System.out.println("Bill for each person is: " + individualBill);
			// End the try code block and catch a possible ArithmeticException
        ____ ____ (ArithmeticException e) ____
			System.out.println("You didn't provide a positive number of people to split the bill among.");
			// End the catch code block
		____
	}
}
코드 편집 및 실행