ออบเจกต์ Exception
โค้ดชิ้นหนึ่งอาจเกิด exception ได้หลายประเภท วิธีหนึ่งในการรับมือคือการใช้ try-catch ดักจับ exception ทุกประเภท แล้วอาศัยออบเจกต์ exception เพื่อระบุว่าเกิดปัญหาอะไรขึ้น และนำข้อมูลจากออบเจกต์ Exception มาช่วย debug
ในแบบฝึกหัดนี้ จะปรับแอปพลิเคชัน SplitTheBill อีกครั้ง โดยให้ catch รับ Exception แบบทั่วไป แล้วใช้ข้อมูลจากออบเจกต์ Exception เพื่อวิเคราะห์สาเหตุของปัญหา ออบเจกต์ Exception มีข้อมูลที่เป็นประโยชน์มากมาย รวมถึง trace ของเมธอดที่นำไปสู่ปัญหานั้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
คำแนะนำการฝึกหัด
- ในบล็อก catch ให้ดักจับ
Exceptionทุกประเภทด้วยcatch (Exception e) - ใช้ออบเจกต์
Exceptionและตัวอ้างอิง (e) พร้อมเมธอดgetClass()ในบล็อกcatchเพื่อแสดงประเภท (คลาส) ของ exception ที่ถูกดักจับ - ใช้ตัวอ้างอิงออบเจกต์
Exception(e) และเมธอดgetMessage()เพื่อพิมพ์ข้อความของ exception - พิมพ์ "stack trace" ออกไปยัง output stream โดยใช้ตัวอ้างอิงออบเจกต์
Exception(e) และเมธอดprintStackTrace()
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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) {
try {
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// Catch any exception
} catch (____ ____) {
System.out.println("You didn't provide a positive number of people to split the bill among.");
// Print the type (class) of exception
System.out.println("Type of exception: " + ____.____());
// Print the exception message
System.out.println(____.____());
// Print the stack trace
____.____();
}
}
}