LoslegenKostenlos loslegen

Finally

Now, modify the previous SplitTheBill calculator of the last exercise to use a finally to print out the bill per individual even when an Exception was caught.

Diese Übung ist Teil des Kurses

Data Types and Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • Add a try and the start of the try code block.
  • Finish the catch code block and add a finally code block.
  • Finish the finally code block.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

import java.math.BigDecimal;

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
        ____
	}
}
Code bearbeiten und ausführen