Kom igångKom igång gratis

Finally

Modifiera nu den tidigare SplitTheBill-kalkylatorn från förra övningen så att den använder ett finally-block för att skriva ut notan per person – även när ett Exception har fångats.

Den här övningen är en del av kursen

Datatyper och undantag i Java

Visa kurs

Övningsinstruktioner

  • Lägg till ett try och starten på try-kodblocket.
  • Avsluta catch-kodblocket och lägg till ett finally-kodblock.
  • Avsluta finally-kodblocket.

Interaktiv övning med praktiskt arbete

Testa den här övningen genom att slutföra den här exempelkoden.

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
        ____
	}
}
Redigera och kör kod