Try-catch
Captura una posible excepción aritmética —división por cero— y manéjala mostrando un mensaje. También podrás ver más usos del paquete BigDecimal, que ya está precargado para ti.
Este ejercicio forma parte del curso
Tipos de datos y excepciones en Java
Instrucciones del ejercicio
- Añade un
tryy el inicio del bloque de códigotry. - Captura la
ArithmeticExceptioncon(ArithmeticException e)e inicia un bloque de códigocatch. - Termina el bloque de código
catch.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
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
____
}
}