Selenium Exception Lookup — Causes & Fixes
Hit an exception mid-run, or got asked one in an interview? This free Selenium exception lookup covers the exceptions every SDET meets — each with its root cause, when it shows up, the Java fix you can paste, and the crisp answer that lands in an interview panel.
The exceptions worth knowing cold
A handful of Selenium exceptions account for most flaky-test pain and most interview questions: StaleElementReferenceException, NoSuchElementException, TimeoutException, ElementClickInterceptedException and ElementNotInteractableException. For each, know the one-line cause and the fix by heart — it signals real hands-on experience faster than almost anything else.
From error message to fix
Search by the exception name or by what you were doing (“click”, “stale”, “timeout”). Each entry gives the root cause, the scenarios that trigger it, and a ready Java fix — usually an explicit wait on the right condition, a re-locate of the element, or a scroll-into-view. Copy the snippet, adapt the locator, and move on.
Selenium exceptions reference — cause, fix & interview answer
Every Selenium exception below is written out in full — name, root cause, when it fires, a Java fix you can paste, and a concise answer for interviews. Use the search tool above for a quick lookup, or read straight through.
NoSuchElementException
How often you hit it: 🔴 Very High
Root cause: Element not found in DOM at the time of lookup.
When it happens:
- Wrong locator (typo in XPath/CSS)
- Element inside iframe — not switched
- Element not yet loaded (needs wait)
- Element in shadow DOM
Java fix:
// FIX 1: Add explicit wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("submit")));
// FIX 2: Switch to iframe first
driver.switchTo().frame("frameName");
driver.findElement(By.id("submit")).click();
driver.switchTo().defaultContent();Interview answer: I first check if the locator is correct using browser DevTools. If yes, I add an explicit wait using WebDriverWait + presenceOfElementLocated. If it's inside an iframe, I switch to the frame first.
StaleElementReferenceException
How often you hit it: 🔴 Very High
Root cause: Element was found, but the DOM was refreshed/updated before action was performed. The element reference is now 'stale'.
When it happens:
- Page reload or AJAX update between find and use
- Navigation happened between findElement and action
- React/Angular re-rendering component
Java fix:
// FIX: Re-find element just before use
public void clickWithRetry(By locator) {
int attempts = 0;
while (attempts < 3) {
try {
driver.findElement(locator).click();
break;
} catch (StaleElementReferenceException e) {
attempts++;
}
}
}
// OR: Use Page Factory with @FindBy — handles re-lookup automaticallyInterview answer: StaleElementReferenceException means the element was found but the DOM changed before I interacted with it. I handle it by re-finding the element in a retry loop or using Page Factory which re-looks up elements automatically.
ElementNotInteractableException
How often you hit it: 🔴 Very High
Root cause: Element exists in DOM but cannot be interacted with (click, type etc.).
When it happens:
- Element is hidden (display:none or visibility:hidden)
- Element is disabled
- Another element is overlapping it
- Element is outside viewport (need scroll)
Java fix:
// FIX 1: Wait for element to be clickable
wait.until(ExpectedConditions.elementToBeClickable(By.id("btn")));
// FIX 2: Scroll element into view
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);
// FIX 3: Click via JavaScript if normal click fails
js.executeScript("arguments[0].click();", element);Interview answer: I first wait for elementToBeClickable. If still failing, I scroll the element into view using JavascriptExecutor. If a popup or overlay is blocking it, I dismiss that first. Last resort: JavaScript click.
TimeoutException
How often you hit it: 🔴 Very High
Root cause: WebDriverWait condition was not met within the specified timeout period.
When it happens:
- Page loaded too slowly
- Element never appeared (bug or wrong locator)
- Network latency in test environment
- Timeout value too short
Java fix:
// FIX 1: Increase timeout for slow environments
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
// FIX 2: Use FluentWait with polling
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
// FIX 3: Check if it's a real bug — element may never appearInterview answer: TimeoutException means my wait condition wasn't met in time. I first check if the element actually appears manually. If yes, I increase the timeout or use FluentWait with shorter polling. If no — it might be a real defect.
WebDriverException: Element click intercepted
How often you hit it: 🟡 High
Root cause: Click was intercepted by another element overlaying the target (popup, cookie banner, toast notification, modal).
When it happens:
- Cookie consent popup covering the element
- Loading spinner overlay still visible
- Toast notification in the way
- Fixed header covering the element after scroll
Java fix:
// FIX 1: Dismiss the overlay first
driver.findElement(By.id("cookie-accept")).click();
// FIX 2: Wait for overlay to disappear
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("spinner")));
// FIX 3: JavaScript click bypasses overlay
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
// FIX 4: Scroll past fixed header
js.executeScript("window.scrollBy(0, -100);"); // scroll up a bitInterview answer: Click intercepted means something is overlaying my target element. I identify the overlay (popup, spinner, banner), dismiss or wait for it to disappear, then retry the click. JavaScript click as fallback.
InvalidSelectorException
How often you hit it: 🟡 Medium
Root cause: The XPath or CSS selector syntax is invalid.
When it happens:
- Typo in XPath/CSS expression
- Special characters not escaped
- Using invalid XPath functions
- CSS selector syntax error
Java fix:
// BAD XPath — causes error:
// driver.findElement(By.xpath("//div[@class='btn primary']")) // space in class
// GOOD — use contains():
driver.findElement(By.xpath("//div[contains(@class,'btn')]"));
// GOOD — CSS equivalent:
driver.findElement(By.cssSelector("div.btn.primary"));
// Validate XPath in browser: Ctrl+F in DevTools → paste XPathInterview answer: InvalidSelectorException means my locator syntax is wrong. I validate XPath in browser DevTools (Ctrl+F). For classes with spaces, I use contains() in XPath or dot notation in CSS selectors.
NoSuchFrameException
How often you hit it: 🟡 Medium
Root cause: Attempted to switch to a frame that doesn't exist or isn't available yet.
When it happens:
- Frame name/id is wrong
- Frame hasn't loaded yet
- Already inside a frame (need to go to defaultContent first)
Java fix:
// FIX: Wait for frame to be available then switch
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frameId")));
// FIX: Always return to default before switching frames
driver.switchTo().defaultContent(); // return to main
driver.switchTo().frame("targetFrame"); // switch to new frame
// FIX: Use index if name unknown
driver.switchTo().frame(0); // first frame on pageInterview answer: I use ExpectedConditions.frameToBeAvailableAndSwitchToIt() to wait for the frame to load. I always call defaultContent() before switching to avoid nested frame issues.
NoAlertPresentException
How often you hit it: 🟡 Medium
Root cause: Attempted to switch to or accept an alert that isn't present.
When it happens:
- Alert dismissed automatically before switchTo
- Alert triggered by async action — need to wait
- No alert is present (code logic error)
Java fix:
// FIX: Wait for alert then handle
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // OK
// alert.dismiss(); // Cancel
// FIX: Check for alert safely
try {
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (NoAlertPresentException e) {
// No alert — continue
}Interview answer: I wait for the alert using alertIsPresent() before switching. For conditional alerts, I wrap in try-catch and proceed if no alert is found.
SessionNotFoundException
How often you hit it: 🟡 Medium
Root cause: WebDriver session no longer exists — browser was closed or crashed.
When it happens:
- Browser closed by external process
- Test tried to use driver after quit()
- Browser crashed during test
- Driver not properly initialised (null)
Java fix:
// FIX: Ensure driver is initialised before use
if (driver == null) {
driver = new ChromeDriver();
}
// FIX: Use ThreadLocal for parallel execution
private static ThreadLocal<WebDriver> driverThread = new ThreadLocal<>();
// FIX: Proper teardown — quit only once in @AfterSuite/@AfterMethod
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
driver = null;
}
}Interview answer: SessionNotFoundException usually means the browser crashed or the driver was used after quit(). I ensure ThreadLocal WebDriver management for parallel tests and null-check before any driver operation.
ElementClickInterceptedException (detailed)
How often you hit it: 🟡 Medium
Root cause: More specific — a different element received the click instead of the target.
When it happens:
- Dropdown opened wrong item
- Cookie banner loaded after element was found
- Another element moved in front during animation
Java fix:
// FIX: Explicit wait for element to stabilise
Thread.sleep(500); // only as last resort — prefer:
wait.until(ExpectedConditions.elementToBeClickable(element));
// FIX: Actions class for complex clicks
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
// FIX: Check page stability before clicking
wait.until(driver -> ((JavascriptExecutor) driver)
.executeScript("return document.readyState").equals("complete"));Interview answer: If a click is intercepted, I wait for the element to be clickable and for the page to be fully loaded. For animated elements, I use Actions class to precisely move to and click the element.
UnexpectedAlertPresentException
How often you hit it: 🟢 Medium
Root cause: An unexpected alert appeared during test execution, blocking the test.
When it happens:
- Server-side error triggered alert
- Application bug showing unexpected popup
- Browser security alert (self-signed cert)
Java fix:
// FIX: Set unexpected alert behaviour in capabilities
ChromeOptions options = new ChromeOptions();
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
driver = new ChromeDriver(options);
// FIX: Handle in test with try-catch
try {
// test action
} catch (UnexpectedAlertPresentException e) {
driver.switchTo().alert().dismiss();
// log as defect — unexpected alert is likely a bug
}Interview answer: An unexpected alert is usually a bug worth logging. I handle it by configuring ChromeOptions to auto-dismiss, or catching and dismissing in test code, then logging the alert text as a defect.
MoveTargetOutOfBoundsException
How often you hit it: 🟢 Low-Medium
Root cause: Actions.moveToElement() target is outside the visible browser area.
When it happens:
- Element is off-screen
- Browser window is too small
- Element inside a scrollable container
Java fix:
// FIX: Scroll element into view first
((JavascriptExecutor) driver)
.executeScript("arguments[0].scrollIntoView(true);", element);
// Then perform action
// FIX: Maximise window
driver.manage().window().maximize();
// FIX: Use Actions with offset
Actions actions = new Actions(driver);
actions.moveToElement(element, 0, 0).click().perform();Interview answer: I scroll the element into view using JavaScript before using Actions. I also always maximise the browser window in test setup to avoid viewport issues.
WebDriverException: Chrome not reachable
How often you hit it: 🟡 Medium
Root cause: ChromeDriver lost connection to the Chrome browser.
When it happens:
- Chrome version mismatch with ChromeDriver
- Chrome crashed during test
- Firewall blocking ChromeDriver port
- ChromeDriver process killed by OS
Java fix:
// FIX 1: Use WebDriverManager (auto-manages versions)
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
// FIX 2: Add retry logic for flaky session start
int attempts = 0;
while (attempts < 3) {
try {
driver = new ChromeDriver();
break;
} catch (WebDriverException e) {
attempts++;
Thread.sleep(2000);
}
}Interview answer: Chrome not reachable is usually a version mismatch. I use WebDriverManager to automatically manage ChromeDriver versions. If it persists, I check if another ChromeDriver process is hanging and kill it.
InvalidElementStateException
How often you hit it: 🟡 Medium
Root cause: Element is in a state where the action cannot be performed (e.g. typing into a read-only field).
When it happens:
- Input field is read-only
- Input is disabled
- Select element trying to be typed into
- Element state changed between find and action
Java fix:
// FIX: Check element state before action
WebElement el = driver.findElement(By.id("input"));
if (el.isEnabled() && !el.getAttribute("readonly").equals("true")) {
el.clear();
el.sendKeys("test data");
}
// FIX: For disabled fields — use JavaScript
((JavascriptExecutor) driver)
.executeScript("arguments[0].removeAttribute('disabled');", el);
// Note: Removing disabled is for testing purposes onlyInterview answer: I check element.isEnabled() and the readonly attribute before interacting. If the field is disabled intentionally, I log it as a test scenario gap. For workarounds, JavaScript can remove the attribute.
NotFoundException (Selenium 4)
How often you hit it: 🟢 Low
Root cause: Base exception for NoSuchElement and NoSuchFrame in Selenium 4. Generic element lookup failure.
When it happens:
- Same as NoSuchElementException — see row 1.
Java fix:
// Same fixes as NoSuchElementException
// Selenium 4 unifies these under NotFoundException
wait.until(ExpectedConditions.presenceOfElementLocated(locator));Interview answer: NotFoundException in Selenium 4 is the parent of NoSuchElementException and NoSuchFrameException. I handle it the same way — add explicit waits and verify locator accuracy.
ScriptTimeoutException
How often you hit it: 🟢 Low
Root cause: JavaScript executed via JavascriptExecutor didn't complete within the script timeout.
When it happens:
- Infinite loop in JavaScript
- Async script didn't call callback
- Script timeout set too low
Java fix:
// FIX: Increase script timeout
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(30));
// FIX: For async scripts, ensure callback is called
((JavascriptExecutor) driver).executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"setTimeout(function(){ callback('done'); }, 2000);");Interview answer: ScriptTimeoutException means my JavaScript execution timed out. I increase the scriptTimeout setting and ensure async scripts call the callback argument correctly.
ConnectionClosedException
How often you hit it: 🟢 Low
Root cause: WebDriver connection to browser or hub was closed unexpectedly.
When it happens:
- Grid hub went down
- Network interruption
- Browser node crashed on Selenium Grid
- Session expired on cloud provider (LambdaTest/Sauce)
Java fix:
// FIX: Add retry at test level
@Test(retryAnalyzer = RetryAnalyzer.class)
public void myTest() { ... }
// RetryAnalyzer:
public class RetryAnalyzer implements IRetryAnalyzer {
int count = 0;
public boolean retry(ITestResult result) {
return count++ < 2; // retry 2 times
}
}
// FIX: Ensure session keepalive for cloud grids
// Check provider docs for timeout settingsInterview answer: ConnectionClosedException on Grid usually means the node went down or cloud session timed out. I implement TestNG RetryAnalyzer for transient failures and check Grid health monitoring.
ElementNotVisibleException (deprecated in Selenium 4)
How often you hit it: 🟢 Low
Root cause: Element exists but is not visible. Replaced by ElementNotInteractableException in Selenium 4.
When it happens:
- Element has display:none or visibility:hidden or opacity:0.
Java fix:
// Selenium 4 — use ElementNotInteractableException handling
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
// Check visibility in test:
boolean isVisible = element.isDisplayed();
// JS to check:
Boolean visible = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].offsetWidth > 0 " +
"&& arguments[0].offsetHeight > 0;", element);Interview answer: In Selenium 4, this is merged into ElementNotInteractableException. I wait for visibilityOfElementLocated. If the element must be invisible for a test case, I verify with isDisplayed() returning false.
JavascriptException
How often you hit it: 🟢 Low
Root cause: JavaScript execution via JavascriptExecutor caused an error in the browser console.
When it happens:
- JavaScript syntax error in script
- Null reference in JS (element not found by JS)
- Browser security restriction blocked JS
Java fix:
// FIX: Wrap JS in try-catch with error handling
try {
Object result = ((JavascriptExecutor) driver)
.executeScript("return document.getElementById('btn').click();");
} catch (JavascriptException e) {
System.out.println("JS Error: " + e.getMessage());
// Fall back to Selenium click
driver.findElement(By.id("btn")).click();
}Interview answer: A JavascriptException means my JS script has an error. I check the script syntax, handle null cases in JS, and fall back to standard Selenium actions if JS fails.
NullPointerException (in Selenium context)
How often you hit it: 🔴 Very High
Root cause: Not a Selenium exception — but most common crash in automation code. WebDriver is null.
When it happens:
- WebDriver not initialised before use
- @BeforeMethod didn't run (dependency issue)
- ThreadLocal driver not set for current thread
- findElement returned null (not possible in Selenium — throws exception instead)
Java fix:
// FIX: Always initialise driver before test
@BeforeMethod
public void setUp() {
driver = new ChromeDriver(); // or ThreadLocal
}
// FIX: Null-safe check
if (driver != null) {
driver.findElement(By.id("test"));
}
// FIX: ThreadLocal pattern
private static ThreadLocal<WebDriver> tlDriver = new ThreadLocal<>();
public static WebDriver getDriver() {
return tlDriver.get();
}Interview answer: NullPointerException on driver means WebDriver wasn't initialised. I ensure @BeforeMethod always runs before @Test, use ThreadLocal for parallel execution, and add null checks in utility methods.
How to use this tool
- Type an exception name or a symptom like “stale” or “timeout”.
- Expand the match to see root cause and when it happens.
- Copy the Java fix and adapt the locator to your page.
- Read the interview answer to explain it crisply in a panel.
Frequently asked questions
Is this lookup free?
Yes, it runs in your browser with nothing to install.
What causes StaleElementReferenceException?
The element reference you held became invalid because the DOM re-rendered. Re-locate the element right before you interact with it, or wait for the new element to be present.
How do I fix intermittent NoSuchElementException?
Almost always a timing issue — replace sleeps with an explicit wait on the exact condition (presence, visibility or clickability) for that element.
Are these good interview answers?
Each exception includes a concise interview-ready answer, because knowing the cause and fix of common exceptions is one of the most common practical Selenium interview checks.