Exception Handling in Selenium Webdriver (Types)

⚡ Smart Summary

Exception handling in Selenium WebDriver keeps a failing command from stopping an entire test run. Java try-catch, multiple catch blocks, throw, throws and finally each give a script a different way to recover.

  • 🔘 Definition: An exception is an error raised while a program executes, and an unhandled one crashes the run.
  • ☑️ Scope: Selenium WebDriver ships more than forty exception classes, and every one of them descends from WebDriverException.
  • Frequent offenders: NoSuchElementException, TimeoutException, StaleElementReferenceException and ElementNotInteractableException cause most real-world failures.
  • 🧪 Handling: A try-catch pair isolates one error type, multiple catch blocks separate several, and finally always executes.
  • 🛠️ Escalation: The throw and throws keywords pass an exception back to the caller when the current method cannot resolve it.
  • 📊 Diagnosis: printStackTrace(), toString() and getMessage() each report a different level of detail about the failure.

Exception handling in Selenium WebDriver with try-catch, throw and finally

What is an Exception?

An exception is an error that happens at the time of execution of a program. While a program runs, the programming language generates an exception that must be handled, otherwise the program crashes.

The exception indicates that, although the event can occur, this type of event happens infrequently. When a method is not able to handle the exception, it is thrown to its caller function. In Java, which drives most Selenium suites, every WebDriver exception is unchecked, so the compiler never forces you to catch it — an unhandled failure surfaces only at run time.

Types of Exceptions in Selenium WebDriver

WebDriverException is the base class of the hierarchy, and every exception below inherits from it. The table lists all 41 exceptions you may meet, together with the condition that raises each one.

# Exception When it occurs
1 ElementNotVisibleException An existing element in the DOM has a feature set as hidden.
2 ElementNotSelectableException The element is in the DOM but cannot be selected, so interaction is impossible.
3 NoSuchElementException The element could not be found with the locator supplied.
4 NoSuchFrameException The frame target to be switched to does not exist.
5 NoAlertPresentException A switch to an alert runs when no alert is presented.
6 NoSuchWindowException The window target to be switched to does not exist.
7 StaleElementReferenceException The web element is detached from the current DOM.
8 SessionNotFoundException The WebDriver acts after you quit the browser.
9 TimeoutException A command did not complete in time — for example, the element searched for was not found within the wait.
10 WebDriverException Base class of the other WebDriver exceptions; also raised when the WebDriver acts right after you close the browser.
11 ConnectionClosedException There is a disconnection in the driver.
12 ElementClickInterceptedException The element receiving the events is concealing the element requested for the click.
13 ElementNotInteractableException The element is present in the DOM, but it is impossible to interact with it.
14 ErrorInResponseException Something failed while interacting with the Firefox extension or the remote driver server.
15 ErrorHandler.UnknownServerException Used as a placeholder when the server returns an error without a stack trace.
16 ImeActivationFailedException IME engine activation has failed.
17 ImeNotAvailableException IME support is unavailable.
18 InsecureCertificateException Navigation made the user agent hit a certificate warning, which an invalid or expired TLS certificate can cause.
19 InvalidArgumentException An argument does not belong to the expected type.
20 InvalidCookieDomainException A cookie is added under a different domain instead of the current URL.
21 InvalidCoordinatesException The interacting operation matched is not valid.
22 InvalidElementStateException The command cannot be finished because the element is invalid.
23 InvalidSessionIdException The given session ID is not among the active sessions, so it does not exist or is inactive.
24 InvalidSwitchToTargetException The frame or window target to be switched to does not exist.
25 JavascriptException An error arose while executing JavaScript given by the user.
26 JsonException The session is requested when the session is not created.
27 NoSuchAttributeException The attribute of an element could not be found.
28 MoveTargetOutOfBoundsException The target provided to the ActionChains move() method is not valid — for example, out of the document.
29 NoSuchContextException ContextAware, which does mobile device testing, cannot find the requested context.
30 NoSuchCookieException No cookie matching the given path name was found among the cookies of the currently browsing document.
31 NotFoundException A subclass of WebDriverException, raised when an element on the DOM does not exist.
32 RemoteDriverServerException The server is not responding because the capabilities described are not proper.
33 ScreenshotException It is not possible to capture a screen.
34 SessionNotCreatedException A new session could not be successfully created.
35 UnableToSetCookieException A driver is unable to set a cookie.
36 UnexpectedTagNameException A support class did not get a web element as expected.
37 UnhandledAlertException There is an alert, but WebDriver is not able to perform the alert operation.
38 UnexpectedAlertPresentException An unexpected alert appears.
39 UnknownMethodException The requested command matches a known URL but not a method for that specific URL.
40 UnreachableBrowserException The browser cannot be opened, or it crashed for some reason.
41 UnsupportedCommandException The remote WebDriver does not send valid commands as expected.

Three dominate daily debugging: NoSuchElementException means a wrong XPath or an element that has not rendered, TimeoutException means a wait too short for an AJAX response, and StaleElementReferenceException follows a dynamic re-render.

How to Handle Exceptions in Selenium

Here are the standard constructs for handling exceptions in Selenium WebDriver. Each is plain Java, so it works in any WebDriver script without extra libraries.

Step 1) Try-catch

This method can catch exceptions using a combination of the try and catch keywords. The try command marks the start of the block, and catch is placed at the end of the try block, where it resolves the exception.

try
{
// Code
} catch (Exception e) {
// Code for Handling exception
}

Step 2) Multiple catch blocks

There are various types of exceptions, and a single block of code can raise more than one. Multiple catch blocks let you handle every type separately with its own code. You may use more than two catch blocks, and there is no limit on how many you add.

try
{
//Code
} catch (ExceptionType1 e1) {
//Code for Handling Exception 1
} catch (ExceptionType2 e2) {
//Code for Handling Exception 2
}

Step 3) Throw

When you want to generate an exception, the throw keyword hands it on to be handled at run time. Use throw when you are passing an exception onward instead of resolving it in the current method.

public static void anyFunction() throws Exception{

try {
// write your code here
} catch (Exception b) {
// Do whatever you want to perform 
// Throw the Exception back to the system
throw(b);
}
}

Step 4) Multiple Exceptions

You can mention various exceptions in the throws clause.

public static void anyFunction() throws ExceptionType1, ExceptionType2{

try {
// write your code here
} catch (ExceptionType1 e1) {
// Code to handle exception 1
} catch (ExceptionType2 e2) {
// Code to handle exception 2
}

Step 5) Finally

The finally keyword creates a block beneath the try block. It executes irrespective of whether an exception occurred, which makes it the right place to close a driver or release a file handle.

try {
//Code
} catch (ExceptionType1 e1) {
//Catch block
} catch (ExceptionType2 e2) {
//Catch block
} catch (ExceptionType3 e3) {
//Catch block
} finally {
//The finally block always executes.
}

Methods for Displaying Exception Information

Once an exception is caught, the object itself carries the diagnostic detail. You can use the following methods to display it:

Method What it reports
printStackTrace() Prints the stack trace, the name of the exception and other useful description.
toString() Returns a text message describing the exception name and description.
getMessage() Displays the description of the exception on its own.

Pair these with a screenshot taken inside the catch block, and a failed run shows both what broke and how the page looked.

FAQs

Every WebDriver exception is unchecked, because they all extend RuntimeException through WebDriverException. The compiler therefore never demands a try-catch, which is convenient, but it also means an unguarded locator failure only shows up when the test actually runs.

Re-locate the element immediately before you act on it instead of caching the reference. A short retry loop that ignores the exception and fetches the node again handles React or Vue re-renders far more reliably than a longer sleep.

They reduce it sharply but never remove it. An explicit wait fixes timing problems only — a wrong locator, an intercepted click or a closed session still raises an exception that nothing but a catch block can absorb.

Selenium 4 keeps the same hierarchy, but wait constructors now take a Duration instead of an integer timeout, and stricter W3C argument validation means InvalidArgumentException surfaces for values that Selenium 3 accepted without complaint.

Self-healing locator engines track which selectors break and swap in a working alternative, which removes a large share of NoSuchElementException failures. Similar models cluster repeated stack traces so a genuinely new defect is not buried among flaky reruns.

Copilot is strong on boilerplate — a try-catch skeleton, a catch chain in the right order, a finally block that quits the driver. It cannot know which exceptions your own application throws, so review every generated catch.

They complement it. An ITestListener centralises logging and screenshots for any test that fails, which keeps the test body clean. Reach for try-catch only where the script must carry on after the error rather than simply report it.

Cast the driver to TakesScreenshot inside the catch or finally block and write the file before the session closes. Naming the image after the test method makes a failed CI run readable without reproducing the fault locally.

Summarize this post with: