MulaiMulai sekarang secara gratis

Finally

Sekarang, ubah kalkulator SplitTheBill dari latihan sebelumnya agar menggunakan finally untuk mencetak tagihan per orang, bahkan ketika sebuah Exception tertangkap.

Latihan ini adalah bagian dari kursus

Tipe Data dan Exception di Java

Lihat Kursus

Petunjuk latihan

  • Tambahkan try dan awal blok kode try.
  • Selesaikan blok kode catch dan tambahkan blok kode finally.
  • Selesaikan blok kode finally.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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
        ____
	}
}
Edit dan Jalankan Kode