how to handle arrayindexoutofboundsexception in Java

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:

  1. WebDriver InitializationWebDriver driver = null;
    • Here, the WebDriver instance driver is declared but not initialized.
    • In a real Selenium test, driver would need to be initialized with a browser driver like new ChromeDriver() or new FirefoxDriver() before interacting with a web page.
  2. Finding Web ElementsList<WebElement> elements = driver.findElements(By.tagName("a"));
    • This finds all <a> (anchor/link) tags on the current web page and stores them in a List<WebElement>.
    • If no links are found, elements will be an empty list, not null.
  3. Accessing an Invalid Indexelements.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()) throws IndexOutOfBoundsException (or more specifically, ArrayIndexOutOfBoundsException in array contexts).
  4. Why This Happens in Selenium Tests
    • Even if the list has 5 links, the indices are 0, 1, 2, 3, 4.
    • elements.size() would be 5.
    • elements.get(5) → Invalid → exception thrown.

Key Points:

Correct way to access the last element:

  • Always ensure you access indices from 0 to elements.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);

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x