如果 Java 程式中沒有處理異常會發生什麼?


異常是在程式執行過程中發生的錯誤(執行時錯誤)。為了理解起見,讓我們以不同的方式來看待它。

通常,當你編譯一個程式時,如果它編譯成功,就會建立一個 .class 檔案,這是 Java 中的可執行檔案,每次你執行這個 .class 檔案時,它都應該成功執行,逐行執行程式中的每一行程式碼,沒有任何問題。但是,在某些特殊情況下,在執行程式時,JVM 會遇到一些不明確的情況,它不知道該怎麼做。

以下是一些示例場景:

  • 如果你有一個大小為 10 的陣列,如果程式碼中的一行試圖訪問該陣列中的第 11 個元素。
  • 如果你試圖用 0 除以一個數字(結果為無窮大,而 JVM 不知道如何評估它)。

此類情況稱為異常。每個可能的異常都由一個預定義的類表示,你可以在 java.lang 包中找到所有異常類。你也可以定義自己的異常。

某些異常在編譯時提示,稱為編譯時異常或檢查異常。

當發生此類異常時,你需要使用 try-catch 塊來處理它們,或者使用 throws 關鍵字丟擲它們(推遲處理)。

如果你不處理異常

當發生異常時,如果你不處理它,程式會突然終止,並且導致異常的那一行程式碼之後的程式碼將不會被執行。

示例

通常,陣列是固定大小的,每個元素都使用索引訪問。例如,我們建立了一個大小為 7 的陣列。那麼訪問該陣列元素的有效表示式將是 a[0] 到 a[6](長度-1)。

每當你使用負值或大於或等於陣列大小的值時,都會丟擲 ArrayIndexOutOfBoundsException 異常。

例如,如果你執行以下程式碼,它會顯示陣列中的元素並要求你提供索引以選擇一個元素。由於陣列的大小為 7,因此有效索引將為 0 到 6。

示例

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("Elements in the array are: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element: ");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}

但是,如果你觀察下面的輸出,我們請求了索引為 9 的元素,因為它是一個無效的索引,因此引發了 ArrayIndexOutOfBoundsException 異常並終止了執行。

執行時異常

Elements in the array are:
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
   at AIOBSample.main(AIOBSample.java:12)

解決方案

為了解決這個問題,你需要透過將負責它的程式碼包裝在 try-catch 塊中來處理異常。

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("Elements in the array are: ");
      System.out.println(Arrays.toString(myArray));
      try {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter the index of the required element: ");
         int element = sc.nextInt();
         System.out.println("Element in the given index is :: "+myArray[element]);
      }catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("Please enter the valid index (0 to 6)");
      }
   }
}

輸出

Elements in the array are:
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
Enter the index of the required element:
7
Please enter the valid index (0 to 6)

更新於: 2020-07-02

3K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.