Finally
Pas nu de eerdere SplitTheBill-calculator uit de vorige oefening aan om een finally te gebruiken dat de rekening per persoon afdrukt, zelfs wanneer er een Exception is opgevangen.
Deze oefening maakt deel uit van de cursus
Gegevenstypen en uitzonderingen in Java
Oefeninstructies
- Voeg een
trytoe en het begin van hettry-codeblok. - Maak het
catch-codeblok af en voeg eenfinally-codeblok toe. - Maak het
finally-codeblok af.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
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) {
BigDecimal individualBill = new BigDecimal(0);
BigDecimal numPeople = new BigDecimal(people);
// Add a try and the beginning of the try code block
____ ____
individualBill = bill.divide(numPeople);
} catch (ArithmeticException e) {
System.out.println("You didn't provide a positive number of people to split the bill among. Assuming 2 people.");
numPeople = new BigDecimal(2);
individualBill = bill.divide(numPeople);
// End the catch code block and add a finally block
____ ____ ____
System.out.println("Bill for each of " + numPeople + " persons is: " + individualBill);
// End the finally block
____
}
}