An exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects. This is a language-independent tag.
An IndexOutOfBoundsException
is an exception that occurs when you attempt to access an object that is outside the boundaries of the container. Common containers are arrays or array-based objects.
IndexOutOfBoundsExceptions
are generally caused by one of 2 things...
- Passing a negative pointer index
- Passing a pointer that is equal-to, or greater than the length of the container.
If we use the example of an array which is defined as being able to hold 4 objects...
Object[] myArray = new Object[4];
Arrays, and array-based containers, in most languages have zero-based references (See Wikipedia for a list of exceptions). This means that the first item in the array is myArray[0]
, not myArray[1]
. For new programmers, this is often not obvious, and can result in them trying to reference objects from 1-4
rather than 0-3
. This causes the programmer to receive an IndexOutOfBoundsException
when trying to reference myArray[4]
.
A common way to make this mistake is to use a for
loop as follows:
for (int i=0; i<=myArray.Length; i++)
// do something with myArray[i];
This will fail with an IndexOutOfBoundsException
because only elements [0]
through [3]
exist. myArray[myArray.Length]
is myArray[4]
, which does not exist.
Similarly, trying to reference a negative index, such as myArray[-1]
will fail, as it exists outside the bounds of the array. This would commonly occur when trying to obtain an index reference from another method, where the method is using a negative number to indicate a failure.
For example, assume the following code...
String myName = "Fred";
Object myObject = myArray[myName.getIndexOf("B")];
In this example, the getIndexOf("B")
method will find the position of the letter B
in the given String
. However, when trying to use this method in the code above, the letter B
is not found in the word Fred
, therefore it returns -1
to indicate it was not found. If we then attempt to use that value as a reference to an item of an array, it will fail.
To help avoid these exceptions, it is usually good practice to perform a check before attempting to reference an item of a collection. For example...
int indexPointer = 2;
if (indexPointer >= 0 && indexPointer < myArray.length){
// the index is within the bounds of the array
Object myObject = myArray[indexPointer];
}