ArrayIndexOutOfBoundsException和IndexOutOfBoundsException之间的区别是什么?

15
我们应该在什么情况下使用ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsException

谷歌 “IndexOutOfBoundsException” - Mohammed Aouf Zouag
区别在于一个用于 n 数组的情况,而另一个则不是。 - Tom
4个回答

23

来自docs.oracle.com文档页面,

IndexOutOfBoundsException:抛出以指示某种索引(例如数组、字符串或向量的索引)超出范围。

ArrayIndexOutOfBoundsExceptionStringIndexOutOfBoundsException是两个类,它们实现了IndexOutOfBoundsException

ArrayIndexOutOfBoundsException:抛出以指示使用非法索引访问数组。索引为负数或大于等于数组大小。

StringIndexOutOfBoundsException:由String方法抛出,以指示索引为负数或大于字符串大小。对于一些方法,如charAt方法,当索引等于字符串大小时也会抛出此异常。


4

IndexOutOfBoundsExceptionArrayIndexOutOfBoundsException(在数组中访问无效索引时抛出)和StringIndexOutOfBoundsException(在字符串中访问无效索引时抛出)的超类。

当访问列表的无效索引时,会抛出基类IndexOutOfBoundsException本身的实例。

一些抛出IndexOutOfBoundsException或其子类的方法的Javadoc包含基类。例如,String.charAt在文档中被记录为抛出IndexOutOfBoundsException,但实际上它抛出的是子类StringIndexOutOfBoundsException


3

如果您越界了访问数组或字符串,您将会得到 ArrayIndexOutOfBoundsException 或者 StringIndexOutOfBoundsException 异常。但是如果访问 LinkedList 或其他集合类,则会得到更通用的 IndexOutOfBoundsException 异常。


0

ArrayIndexOutOfBoundsException 表示其消息中存在非法索引。


2
IndexOutOfBoundsException 不会出现吗? - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接