如何在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("数组大小仅限于5个元素");

      }

   }

}

输出结果

数组大小仅限于5个元素

以上是 如何在Java中捕获数组索引超出范围的异常? 的全部内容, 来源链接: utcz.com/z/350363.html

回到顶部