ArrayIndexOutOfBoundsException is an unchecked exception in Java and is a subclass of the RuntimeException class (which ultimately extends Throwable). This exception occurs when an attempt is made to access an array element using an index that is outside the valid range.
In Java, array indexing starts at 0 and ends at length - 1. If we try to access an List element using an index that is equal to or greater than the size of the list or if we attempt to access an element using a negative index, Java throws an ArrayIndexOutOfBoundsException.
Below, I have explained a scenario that demonstrates how an ArrayIndexOutOfBoundsException can occur in a Selenium automation program written in Java.
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
public class ExceptionCheck {
WebDriver driver = null;
@Test
public void arrayIndexOutOfBoundsException() {
List<WebElement> elements = driver.findElements(By.tagName("a"));
elements.get(elements.size());
}
}
Step-by-step Explanation:
- WebDriver Initialization
WebDriver driver = null;- Here, the WebDriver instance
driveris declared but not initialized. - In a real Selenium test,
driverwould need to be initialized with a browser driver likenew ChromeDriver()ornew FirefoxDriver()before interacting with a web page.
- Here, the WebDriver instance
- Finding Web Elements
List<WebElement> elements = driver.findElements(By.tagName("a"));- This finds all
<a>(anchor/link) tags on the current web page and stores them in aList<WebElement>. - If no links are found,
elementswill be an empty list, not null.
- This finds all
- Accessing an Invalid Index
elements.get(elements.size());- In Java, list indices start at 0 and go up to
size() - 1. elements.size()is one past the last valid index.- Trying to access
elements.get(elements.size())throwsIndexOutOfBoundsException(or more specifically,ArrayIndexOutOfBoundsExceptionin array contexts).
- In Java, list indices start at 0 and go up to
- Why This Happens in Selenium Tests
- Even if the list has 5 links, the indices are
0, 1, 2, 3, 4. elements.size()would be5.elements.get(5)→ Invalid → exception thrown.
- Even if the list has 5 links, the indices are
Key Points:
Correct way to access the last element:
- Always ensure you access indices from
0toelements.size() - 1.
- In Selenium automation, this mistake is common when looping over elements or trying to access the “last element” without subtracting 1.
- Correct way to access the last element:
WebElement lastElement = elements.get(elements.size() - 1);