---
description: What is an Exceptions? An exception is an error that happens at the time of execution of a program. However, while running a program, programming languages generates an exception that should be handle
title: Exception Handling in Selenium Webdriver (Types)
image: https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png
---

 

[Skip to content](#main) 

**⚡ 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.

[ Read More ](javascript:void%280%29;) 

![Exception handling in Selenium WebDriver with try-catch, throw and finally](https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png) 

## 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](https://www.guru99.com/java-tutorial.html), which drives most [Selenium](https://www.guru99.com/selenium-tutorial.html) 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](https://www.guru99.com/locators-in-selenium-ide.html) supplied.                                                                       |
| 4  | **NoSuchFrameException**                | The [frame](https://www.guru99.com/handling-iframes-selenium.html) target to be switched to does not exist.                                                                             |
| 5  | **NoAlertPresentException**             | A switch to an [alert](https://www.guru99.com/alert-popup-handling-selenium.html) 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](https://www.guru99.com/understanding-dom-fool-guide.html).                                                                           |
| 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](https://www.guru99.com/ssl-certificate-error-handling-selenium.html), which an invalid or expired TLS certificate can cause. |
| 19 | **InvalidArgumentException**            | An argument does not belong to the expected type.                                                                                                                                       |
| 20 | **InvalidCookieDomainException**        | A [cookie](https://www.guru99.com/handling-cookies-selenium-webdriver.html) 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](https://www.guru99.com/xpath-selenium.html) or an element that has not rendered, TimeoutException means a wait too short for an [AJAX](https://www.guru99.com/handling-ajax-call-selenium-webdriver.html) response, and StaleElementReferenceException follows a [dynamic](https://www.guru99.com/handling-dynamic-selenium-webdriver.html) re-render.

### RELATED ARTICLES

* [How to Install Selenium WebDriver ](https://www.guru99.com/installing-selenium-webdriver.html "How to Install Selenium WebDriver")
* [XPath Contains: Text, Following Sibling & Ancestor in Selenium ](https://www.guru99.com/using-contains-sbiling-ancestor-to-find-element-in-selenium.html "XPath Contains: Text, Following Sibling & Ancestor in Selenium")
* [How to Run Multiple Test Cases in TestNG Suite ](https://www.guru99.com/testng-execute-multiple-test-suites.html "How to Run Multiple Test Cases in TestNG Suite")
* [How to Take Screenshot in Selenium WebDriver ](https://www.guru99.com/take-screenshot-selenium-webdriver.html "How to Take Screenshot in Selenium WebDriver")

## 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](https://www.guru99.com/first-webdriver-script.html) 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

🧱 Are Selenium exceptions checked or unchecked in Java?

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.

🔁 What stops StaleElementReferenceException from returning?

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.

⏱️ Do explicit waits remove the need for try-catch?

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.

🆕 What changed about exceptions in Selenium 4?

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.

🤖 Can machine learning cut down Selenium exception failures?

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.

🧑‍💻 Is GitHub Copilot useful for writing exception handling?

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.

🧪 Should TestNG listeners replace try-catch blocks?

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.

📸 How do you capture a screenshot when an exception occurs?

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:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png","url":"https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png","width":"700","height":"250","caption":"Exception Handling in Selenium Webdriver","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/exception-handling-selenium.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/selenium","name":"Selenium"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/exception-handling-selenium.html","name":"Exception Handling in Selenium Webdriver (Types)"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/exception-handling-selenium.html#webpage","url":"https://www.guru99.com/exception-handling-selenium.html","name":"Exception Handling in Selenium Webdriver (Types)","dateModified":"2026-07-30T13:33:10+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/exception-handling-selenium.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta","url":"https://www.guru99.com/author/admin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","url":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","caption":"Krishna Rungta","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Selenium","headline":"Exception Handling in Selenium Webdriver (Types)","description":"What is an Exceptions? An exception is an error that happens at the time of execution of a program. However, while running a program, programming languages generates an exception that should be handle","keywords":"selenium","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta"},"dateModified":"2026-07-30T13:33:10+05:30","image":{"@id":"https://www.guru99.com/images/exception-handling-in-selenium-webdriver.png"},"copyrightYear":"2026","name":"Exception Handling in Selenium Webdriver (Types)","subjectOf":[{"@type":"HowTo","name":"How to Handling Exceptions in Selenium","description":"Here, are some important standard using which you can handle Exceptions in Selenium WebDriver:","step":[{"@type":"HowToStep","name":"Step 1) Try-catch","text":"This method can catch Exceptions, which uses a combination of the try and catch keywords.","url":"https://www.guru99.com/exception-handling-selenium.html#step1"},{"@type":"HowToStep","name":"Step 2) Multiple catch blocks","text":"There are various types of Exceptions, and you can expect more than one exception from a single block of code.","url":"https://www.guru99.com/exception-handling-selenium.html#step2"},{"@type":"HowToStep","name":"Step 3) Throw","text":"Throw keyword is used to throw Exception to handle it in the run time.","url":"https://www.guru99.com/exception-handling-selenium.html#step3"},{"@type":"HowToStep","name":"Step 4) Multiple Exceptions","text":"You can mention various Exceptions in the throws clause.","url":"https://www.guru99.com/exception-handling-selenium.html#step4"},{"@type":"HowToStep","name":"Step 5) Finally","text":"The Final keyword is used to create a block of code under the try block.","url":"https://www.guru99.com/exception-handling-selenium.html#step5"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Are Selenium exceptions checked or unchecked in Java?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What stops StaleElementReferenceException from returning?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Do explicit waits remove the need for try-catch?","acceptedAnswer":{"@type":"Answer","text":"They reduce it sharply but never remove it. An explicit wait fixes timing problems only \u2014 a wrong locator, an intercepted click or a closed session still raises an exception that nothing but a catch block can absorb."}},{"@type":"Question","name":"What changed about exceptions in Selenium 4?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can machine learning cut down Selenium exception failures?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Is GitHub Copilot useful for writing exception handling?","acceptedAnswer":{"@type":"Answer","text":"Copilot is strong on boilerplate \u2014 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."}},{"@type":"Question","name":"Should TestNG listeners replace try-catch blocks?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How do you capture a screenshot when an exception occurs?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}],"@id":"https://www.guru99.com/exception-handling-selenium.html#schema-207660","isPartOf":{"@id":"https://www.guru99.com/exception-handling-selenium.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/exception-handling-selenium.html#webpage"}}]}
```
