Java中的数组索引越界异常

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

null

这个 数组下标越界异常 是仅在运行时引发的运行时异常。Java编译器在编译程序时不会检查此错误。

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的另一个示例:

JAVA

// 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)

让我们详细了解一下:

  • 这里的索引定义了我们试图访问的索引。
  • 大小为我们提供了列表大小的信息。
  • 由于大小是2,我们可以访问的最后一个索引是(2-1)=1,因此是异常。

访问阵列的正确方法是:

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

}

正确的代码–

JAVA

// 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(int m : ar){
}

例子:

JAVA

// 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.使用 试着接住 :

考虑将代码封装在一个catch catch语句中,并相应地操作异常。如前所述,Java不允许访问无效索引,并且肯定会抛出ArrayIndexOutOfBoundsException。然而,在catch语句块内部我们应该小心,因为如果我们不适当地处理异常,我们可能会隐藏它,从而在应用程序中创建错误。

JAVA

// 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( "Exception caught" );
}
}
}


输出

1 2 3 4 5 
Exception caught

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

探索 测验 问题

本文由 Rishabh Mahrsee .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以写一篇文章,然后将文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享