空指针异常与数组下标越界异常解析

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

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进行判断所调用内容是否为空

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值