(Re)lançando
Quando um método lança uma exceção, o método que o chama precisa tratá-la. Para isso, ele pode usar try/catch ou relançar a exceção. Neste exercício, você vai ver como um método chamador relança uma exceção.
Este exercicio faz parte do curso
Tipos de Dados e Exceções em Java
Instruções do exercicio
- Chame o método
dineOut()com 9 pessoas para disparar aException. - Como o método
dineOut()não está tratando a exceção, relance aException. - Como o método
splitBill()não está tratando a exceção, lance aException.
exercicio interativo prático
Tente este exercicio completando este código de exemplo.
public class RethrowingExample {
public static void main(String[] args) {
try {
// Trigger the exception by calling dineOut with 9 people
dineOut(____, 50.00);
} catch (Exception e) {
System.out.println("Atempting to divide bill with too many diners");
}
}
// Rethrow the Exception
public static void dineOut(int people, double bill) ____ ____ {
double each = splitBill(bill, people);
System.out.println("Bill for each person: " + each);
}
// Throw the Exception
public static double splitBill(double bill, int people) ____ ____ {
if (people < 3) {
return bill / people;
} else {
throw new Exception();
}
}
}