Selenium WebDriver throws specific exceptions depending on what goes wrong during automation. Here are the most common ones:
1. NoSuchElementException Element could not be found using the locator provided.
// Fix: check locator, add wait, or verify element exists
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username")));
2. ElementNotVisibleException / ElementNotInteractableException Element is present in DOM but not visible or not interactable. Fix: scroll to element or use JavascriptExecutor click.
3. NoAlertPresentException
Trying to switch to an alert that has not appeared yet.
Fix: use ExpectedConditions.alertIsPresent() before switching.
4. NoSuchFrameException Trying to switch to a frame that does not exist. Fix: verify frame name/id and wait for it to be available.
5. NoSuchWindowException
Trying to switch to a window that is not present.
Fix: verify window handle and use getWindowHandles().
6. TimeoutException A wait condition was not met within the timeout period. Fix: increase timeout or check if element actually appears.
7. InvalidElementStateException Element state is not appropriate for the desired action (e.g., typing in a disabled field).
8. NoSuchAttributeException Trying to get an attribute that does not exist on the element.
9. StaleElementReferenceException Element was found but the DOM was refreshed/updated, making the reference stale.
// Fix: re-find the element after DOM update
WebElement el = driver.findElement(By.id("btn"));
driver.navigate().refresh();
el = driver.findElement(By.id("btn")); // re-locate
el.click();
10. WebDriverException General exception when there is an issue with the driver instance itself.
