ArrayIndexOutOfBoundsException 和 IndexOutOfBoundsException 的区别?

问题描述 投票:0回答:4

我们应该在哪些用例中分别使用

ArrayIndexOutOfBoundsException
和 `IndexOutOfBoundsException?

java exception indexoutofboundsexception
4个回答
23
投票

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

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

ArrayIndexOutOfBoundsException
,
StringIndexOutOfBoundsException
是两个类,它们实现了
IndexOutOfBoundsException
.

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

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


4
投票

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

基类的实例

IndexOutOfBoundsException
本身在访问列表的无效索引时被抛出。

一些抛出

IndexOutOfBoundsException
的方法或其子类的Javadoc包含基类。例如,
String.charAt
被记录为在实际抛出子类
IndexOutOfBoundsException
时抛出
StringIndexOutOfBoundsException


3
投票

基本上,如果您超出数组或字符串的范围,您将得到 ArrayIndexOutOfBoundsException 或 StringIndexOutOfBoundsException。 对于 LinkedList though 或其他一些 Collection,您将获得更一般的 IndexOutOfBoundsException。


0
投票

ArrayIndexOutOfBoundsException 指示其消息中的非法索引。

© www.soinside.com 2019 - 2024. All rights reserved.