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