Java 数组索引越界的异常

Java 数组索引越界的异常

Java支持创建和操作数组作为一种数据结构。数组的索引是一个整数,其值在区间[0, n-1]内,其中n是数组的大小。如果请求的索引为负数或大于或等于数组的大小,那么JAVA会抛出ArrayIndexOutOfBounds异常。这与C/C++不同,在C/C++中不做绑定索引的检查。

ArrayIndexOutOfBoundsException 是一个只在运行时抛出的运行时异常。Java编译器在编译程序的过程中不会检查这个错误。

// A Common cause index out of bound
public class NewClass2 {
    public static void main(String[] args)
    {
        int ar[] = { 1, 2, 3, 4, 5 };
        for (int i = 0; i <= ar.length; i++)
            System.out.println(ar[i]);
    }
}

预期的输出

1
2
3
4
5

原始输出

运行时错误抛出了一个异常

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at NewClass2.main(NewClass2.java:5)

如果你仔细看,这里的数组大小是5。因此,当使用for循环访问其元素时,最大的索引值可以是4,但在我们的程序中,它一直到5,因此出现了异常。

让我们看看另一个使用ArrayList的例子。

// One more example with index out of bound
import java.util.ArrayList;
public class NewClass2
{
    public static void main(String[] args)
    {
        ArrayList<String> lis = new ArrayList<>();
        lis.add("My");
        lis.add("Name");
        System.out.println(lis.get(2));
    }
}

这里的运行时错误比前面的时间更有信息量

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at NewClass2.main(NewClass2.java:7)

让我们详细地了解一下。

  • 这里的索引定义了我们要访问的索引。
  • size给了我们关于列表的大小的信息。
  • 由于大小是2,我们可以访问的最后一个索引是(2-1)=1,因此出现了异常。

访问数组的正确方法是:

for (int i=0; i<ar.length; i++){

}

正确的代码 –

// Correct code for Example 1
public class NewClass2 {
    public static void main(String[] args)
    {
        int ar[] = { 1, 2, 3, 4, 5 };
  
        for (int i = 0; i < ar.length; i++)
            System.out.println(ar[i]);
    }
}

输出

1
2
3
4
5

处理异常情况

1.使用for-each循环

这在访问数组元素时自动处理索引。

语法

for(int m : ar){
}

例子

// Handling exceptions using for-each loop
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
          
          int arr[] = {1,2,3,4,5};
        
          for(int num : arr){
               
             System.out.println(num);     
            
        }
    }
}

输出

1
2
3
4
5

2.使用Try-Catch

考虑将你的代码封装在一个 try-catch 语句中,并对异常进行相应的处理。如前所述,Java不会让你访问一个无效的索引,肯定会抛出一个ArrayIndexOutOfBoundsException。然而,我们应该在catch语句的块内小心,因为如果我们不适当地处理异常,我们可能会掩盖它,从而在你的应用程序中产生一个错误。

// Handling exception using try catch block
public class NewClass2 {
    public static void main(String[] args)
    {
        int ar[] = { 1, 2, 3, 4, 5 };
        try {
            for (int i = 0; i <= ar.length; i++)
                System.out.print(ar[i]+" ");
        }
        catch (Exception e) {
            System.out.println("\nException caught");
        }
    }
}

输出

1 2 3 4 5 
Exception caught

在上面的例子中,你可以看到直到索引4(值5),循环打印了所有的值,但是当我们试图访问arr[5]时,程序抛出了一个异常,这个异常被catch块捕获,它打印了 “捕获异常 “语句。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程