admin管理员组

文章数量:1550528

数组下标越界异常是什么?怎么发生?

ArrayIndexOutOfBoundsException的源码开头写明了答案

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

抛出以指示已使用非法索引访问数组。索引为负数,或者大于或等于数组的大小。

即为所使用的数组下标超出了0~(数组长度-1)的这个范围

数组下标越界异常如何解决?

在报出异常信息时会出现错误的具体位置 如下

at work.week01.Array.main(Array.java:6)

查看第6行代码,修改错误的下标即可

如若要对该数组进行扩容,则使用如下方法

int[] arr = new arr[3];//定义长度为3的一维数组
System.out.println(arr[4]);//出现数组下标越界异常
arr = Arrays.copyof(arr , 5);//5即代表着新数组(arr)的长度
System.out.println(arr[4]);//正常运行

空指针异常是什么?

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

  • 调用空对象的实例方法。
  • 访问或修改空对象的字段。
  • 将 null 的长度视为数组。
  • 访问或修改 null 插槽,就好像它是数组一样。
  • 将 null 作为可抛出值一样抛出。

总结起来就是当调用内容为空时抛出的错误

空指针异常解决方法

手动解决,在调用内容前先检查所调用内容是否进行初始化,并使用if进行判断所调用内容是否为空

本文标签: 异常下标数组指针