Difference between ArrayIndexOutOfBoundsException and IndexOutOfBoundsException?

假装没事ソ 提交于 2019-11-29 08:02:28

问题


What are the use cases in which we should use ArrayIndexOutOfBoundsException and `IndexOutOfBoundsException one over another?


回答1:


IndexOutOfBoundsException :Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException are two classes, which have implemented IndexOutOfBoundsException.

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.

StringIndexOutOfBoundsException:Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.




回答2:


IndexOutOfBoundsException is the super class of ArrayIndexOutOfBoundsException (thrown when accessing invalid index in a array) and StringIndexOutOfBoundsException (thrown when accessing invalid index in a String).

Instances of the base class IndexOutOfBoundsException itself are thrown when accessing invalid indices of Lists.

The Javadoc of some methods that throw IndexOutOfBoundsException or its sub-classes contains the base class. For example, String.charAt is documented to be throwing IndexOutOfBoundsException when it actually throws the sub-class StringIndexOutOfBoundsException.




回答3:


ArrayIndexOutOfBoundsException indicates the illegal index in its message.




回答4:


Basically, if you go out of bounds for an array or String, you will get the ArrayIndexOutOfBoundsException or the StringIndexOutOfBoundsException. For a LinkedList though or some other Collection, you will get the more general IndexOutOfBoundsException.



来源:https://stackoverflow.com/questions/34266174/difference-between-arrayindexoutofboundsexception-and-indexoutofboundsexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!