開始使用免費開始

RuntimeException

RuntimeExceptions 在程式碼中不一定需要 try/catch 區塊。通常可以透過良好的程式撰寫習慣來避免。不過,當錯誤未被偵測且 RuntimeException 未被捕捉時,應用程式會失敗,並顯示使用者未必看得懂的問題資訊。在這個練習中,你會看到當你沒有捕捉可能發生的 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.");
		}
	}
}
編輯並執行程式碼