ComeçarComece de graça

Try-catch

Catch a possible arithmetic exception - division by zero - and handle it by displaying a message. You will also get a chance to see more use of the BigDecimal package that has been preloaded for you.

Este exercício faz parte do curso

Data Types and Exceptions in Java

Ver curso

Instruções do exercício

  • Add a try and the start of the try code block.
  • Catch the ArithmeticException with (ArithmeticException e) and start a catch code block.
  • Finish the catch code block.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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
		____
	}
}
Editar e executar o código