如何在 Java 中捕獲超出陣列索引範圍的異常?


當你嘗試訪問超出範圍的陣列元素時,將會引發 ArrayIndexOutOfBoundsException 異常。

示例

即時演示

public class ArrayIndexOutOfBounds {
   public static void main(String args[]) {
      try {
         int[] a = new int[]{1,2,3,4,5};
         int x = 6;
         a[10] = x;
      } catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("Array size is restricted to 5 elements only");
      }
   }
}

輸出

Array size is restricted to 5 elements only

更新於: 2020 年 2 月 20 日

385 次瀏覽

開始您的事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.