Java中的Java .lang.ArrayIndexOutOfBoundsExcepiton 示例
Java.lang.ArrayIndexOutOfBoundsException是运行时异常,仅在程序执行状态时抛出。 Java编译器在编译期间从不检查此错误。
Java.lang.ArrayIndexOutOfBoundsException 是Java中最常见的异常之一。当程序员试图访问数组中无效索引处的元素值时,就会发生这种情况。从 JDK 1.0 版开始, Java中引入了此异常。 ArrayIndexOutOfBoundsException 可能由于多种原因而发生,例如当我们尝试访问数组中一个负索引或大于数组 -1 大小的索引的元素的值时。
下面的代码示例显示了可能发生此错误的情况以及使用 try-catch 块处理和显示错误的情况。
案例 1:- 在负索引处访问元素的值
Java
// Java program to show the ArrayIndexOutOfBoundsException
// while accessing element at negative index
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
int array[] = new int[] { 4, 1, 2, 6, 7 };
// accessing element at index 2
System.out.println("The element at index 2 is "
+ array[2]);
// accessing element at index -1
// this will throw the
// ArrayIndexOutOfBoundsException
System.out.println("The element at index -1 is "
+ array[-1]);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Java
// Java program to show the ArrayIndexOutOfBoundsException
// while accessing element at index greater then size of
// array -1
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
int array[] = new int[] { 4, 1, 2, 6, 7 };
// accessing element at index 4
System.out.println("The element at index 4 is "
+ array[4]);
// accessing element at index 6
// this will throw the
// ArrayIndexOutOfBoundsException
System.out.println("The element at index 6 is "
+ array[6]);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出
The element at index 2 is 2
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
情况 2:-访问索引大于数组大小的元素 -1
Java
// Java program to show the ArrayIndexOutOfBoundsException
// while accessing element at index greater then size of
// array -1
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
int array[] = new int[] { 4, 1, 2, 6, 7 };
// accessing element at index 4
System.out.println("The element at index 4 is "
+ array[4]);
// accessing element at index 6
// this will throw the
// ArrayIndexOutOfBoundsException
System.out.println("The element at index 6 is "
+ array[6]);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出
The element at index 4 is 7
java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5