Throws
เมื่อเกิดข้อยกเว้นขึ้น เมธอดสามารถเลือกจัดการด้วย try-catch หรือจะ throw ข้อยกเว้นนั้นกลับไปยังผู้เรียกใช้ก็ได้ ในแบบฝึกหัดนี้ คุณจะได้เรียนรู้วิธี throw ข้อยกเว้นแทนการจัดการด้วย try/catch
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
คำแนะนำการฝึกหัด
- เพิ่มบล็อก try ครอบโค้ดที่เรียก
getScore(3)และพิมพ์ผลลัพธ์ - เพิ่มบล็อก catch เพื่อจัดการ
ArrayIndexOutOfBoundsExceptionที่เกิดขึ้นในเมธอดgetScore() - ให้เมธอด
getScore(int)throwArrayIndexOutOfBoundsExceptionแทนการใช้ try/catch ภายในเมธอด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
package exceptions;
public class ThrowingExample {
public static int[] scores = { 75, 97, 83 };
public static void main(String[] args) {
// Add a try block
____ {
int lastScore = getScore(3);
System.out.println("Last score:" + lastScore);
// Catch the exception thrown by getScore(int)
} ____ (____ e) {
System.out.println("Tried to access non-existent score");
}
}
// Throw ArrayIndexOutOfBoundsException
public static int getScore(int index) ____ ____ {
return scores[index];
}
}