Try-catch
จับข้อผิดพลาดทางคณิตศาสตร์ที่อาจเกิดขึ้น — การหารด้วยศูนย์ — และจัดการด้วยการแสดงข้อความแจ้งเตือน นอกจากนี้ยังได้ฝึกใช้แพ็กเกจ BigDecimal ที่โหลดไว้ให้แล้วด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
คำแนะนำการฝึกหัด
- เพิ่ม
tryและเปิดบล็อกโค้ดtry - จับ
ArithmeticExceptionด้วย(ArithmeticException e)และเปิดบล็อกโค้ดcatch - ปิดบล็อกโค้ด
catch
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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) {
// Add a try and the beginning of the try code block
____ ____
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// End the try code block and catch a possible ArithmeticException
____ ____ (ArithmeticException e) ____
System.out.println("You didn't provide a positive number of people to split the bill among.");
// End the catch code block
____
}
}