RuntimeException
RuntimeExceptions ไม่จำเป็นต้องมีบล็อก try/catch ในโค้ด โดยส่วนใหญ่สามารถหลีกเลี่ยงได้ด้วยการเขียนโค้ดที่ถูกต้อง อย่างไรก็ตาม หากไม่ตรวจพบข้อผิดพลาดและ RuntimeException ไม่ถูก catch ไว้ แอปพลิเคชันจะหยุดทำงานและแสดงข้อมูล error ที่ผู้ใช้อาจไม่เข้าใจ ในแบบฝึกหัดนี้ จะได้เห็นว่าเกิดอะไรขึ้นเมื่อไม่ catch RuntimeException ที่อาจเกิดขึ้น และเกิดอะไรขึ้นเมื่อใช้ try/catch จัดการกับมัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
คำแนะนำการฝึกหัด
- ตรวจสอบเมธอด
withoutTryCatch()และwithTryCatch()ในแอปพลิเคชันนี้ และสังเกตความแตกต่างระหว่างทั้งสอง - รันแอปพลิเคชันโดยไม่แก้ไขโค้ด ซึ่งจะทำให้เมธอด
withoutTryCatch()ทำงานและเกิดRuntimeExceptionขึ้น - คอมเมนต์บรรทัดที่ 5 และยกเลิกคอมเมนต์บรรทัดที่ 7 จากนั้นรันแอปพลิเคชันอีกครั้ง ซึ่งจะทำให้เมธอด
withTryCatch()ทำงานและจัดการกับRuntimeExceptionได้ในครั้งนี้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class RuntimeExceptionHandling {
public static void main(String[] args) {
// Comment out this line
withoutTryCatch();
// Uncomment this line
// withTryCatch();
}
public static void withoutTryCatch() {
String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
String selectedMount = mounts[4];
System.out.println("Selected item is: " + selectedMount);
}
public static void withTryCatch() {
try {
String[] mounts = { "Everest", "K2", "Kangchenjunga", "Lhotse" };
String selectedMount = mounts[4];
System.out.println("Selected item is: " + selectedMount);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Oops - made a mistake accessing the mounts array with a bad index.");
}
}
}