เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Throws

เมื่อเกิดข้อยกเว้นขึ้น เมธอดสามารถเลือกจัดการด้วย try-catch หรือจะ throw ข้อยกเว้นนั้นกลับไปยังผู้เรียกใช้ก็ได้ ในแบบฝึกหัดนี้ คุณจะได้เรียนรู้วิธี throw ข้อยกเว้นแทนการจัดการด้วย try/catch

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เพิ่มบล็อก try ครอบโค้ดที่เรียก getScore(3) และพิมพ์ผลลัพธ์
  • เพิ่มบล็อก catch เพื่อจัดการ ArrayIndexOutOfBoundsException ที่เกิดขึ้นในเมธอด getScore()
  • ให้เมธอด getScore(int) throw ArrayIndexOutOfBoundsException แทนการใช้ 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];
	}
}
แก้ไขและรันโค้ด