quintin
quintin

Reputation: 837

Difference between ArrayIndexOutOfBoundsException and IndexOutOfBoundsException?

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

Upvotes: 15

Views: 14447

Answers (4)

Ravindra babu
Ravindra babu

Reputation: 38950

From docs.oracle.com documentation pages:

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.

Upvotes: 23

XcodeNOOB
XcodeNOOB

Reputation: 2185

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.

Upvotes: 3

user1326628
user1326628

Reputation:

ArrayIndexOutOfBoundsException indicates the illegal index in its message.

Upvotes: -1

Eran
Eran

Reputation: 394066

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.

Upvotes: 4

Related Questions