java.lang.IndexOutOfBoundsException
java.lang.IndexOutOfBoundsException
The java.lang.IndexOutOfBoundsException is an exception class in Java that is thrown when an index used to access an array, list, or other collection is either negative or greater than or equal to the size of the collection. This usually indicates an attempt to access an element at an invalid index that does not exist in the collection.
For example, if you have an list of webelemnet with a length of 6, the valid indexes to access elements in the lists are 0, 1, 2, 3, 4 and 5. If you attempt to access an element at index 6 or any negative index, an IndexOutOfBoundsException will be thrown.
Here's an example of how you might encounter an IndexOutOfBoundsException:
In the above code, the list of webelement numbers has only six elements with valid indexes 0, 1, 2, 3, 4 and 5. Attempting to access an element at index 6 will result in an IndexOutOfBoundsException. To avoid this exception, make sure that the index you're using to access elements is within the valid range of indexes for the collection you're working with. You can do this by checking the length or size of the collection before attempting to access elements at specific indexes. Here's a How to deal with this exception using try/catch block:
In this corrected example discuss below, the program checks if the index is within the valid range before attempting to access an element. Always ensure that you validate indexes before using them to access elements in arrays, lists, or other collections to avoid encountering an IndexOutOfBoundsException.