開始使用免費開始

Throws

當發生例外時,方法可以選擇用 try-catch 來處理,或是把例外拋給呼叫端(也就是把責任往上傳遞)。在這個練習中,你會看到如何選擇拋出例外,而不是用 try/catch 來處理。

本練習屬於課程

Java 的資料型別與例外狀況

檢視課程

練習說明

  • 在呼叫並列印 getScore(3) 的程式碼外圍加入 try 區塊。
  • 加入 catch 區塊來處理 getScore() 方法造成的 ArrayIndexOutOfBoundsException
  • getScore(int) 改為拋出 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];
	}
}
編輯並執行程式碼