如何在 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.