Exception Handling in Selenium WebDriver

Related Product On This Page What is Exception?April 24, 2026 · 14 min read · Tool Comparison

Related Product

Exception Handling in Selenium WebDriver

Exception handling in Selenium WebDriver is essential for ensuring robust and reliable automated tryout. It allow you to anticipate and manage errors, making tests more resilient and accurate. It helps your exam either recover or fail with clear insights.

Overview

Why Exception Handling in Selenium in Important?

  • Prevents precipitous test failure
  • Provides clear error feedback
  • Handles unexpected issues gracefully
  • Simplifies debug
  • Enhances overall exam dependableness

Consequences of Failing to Use Exception Handling in Selenium:

  • Uncaught Errors Halt Execution
  • Lack of Error Reporting
  • Inconsistent Test Results
  • Inability to Handle Dynamic Content
  • Reduced Maintainability

Mutual Exceptions in Selenium

  • MoveTargetOutOfBoundsException
  • InvalidArgumentException
  • UnhandledAlertException
  • JavascriptException
  • NoAlertPresentException

This guide helps realize and enforce effective exception plow to improve test stability and simplify debugging and maintenance.

What is Exception?

An exception is an incident that agitate the normal stream of a program & # 8217; s execution. When an unexpected happening occur during the execution of a broadcast, an exception object is create to ponder the specific fault or unexpected state.

An Exception could be stimulate by a variety of factors, include:

  • Logical errorsoccur when the code does not run as expected or when improper reasoning causes an unexpected consideration.
  • Runtime mistakeoccur during program execution and are commonly caused by improper comment, division by naught, or attempt to access an regalia element that does not exist.
  • System Errorsoccur when the software experiences challenges with system resources, such as bunk out of memory or experiencing file I/O erroneousness.

To properly handle exceptions, program provide methods such as try-except cube (try-catch in some), in which codification that may cause an exception is trapped within a try block and potential exceptions are get and handled in except blocks. This aid to gracefully manage failures and continue the software stable.

Why is Exception Handling in Selenium Important?

Exception handling is significant because it provides critical information about problems encountered during the execution of automated tryout or browser interactions.

Here are the key reasons why it is important:

  • Prevents abrupt test failure by catching errors.
  • Gracefully handles unexpected issues like timeouts and miss elements.
  • Simplifies debugging with clear erroneousness feedback.
  • Enhances overall test stability and reliability.
  • Supports ordered performance in CI/CD environs.

Consequences of Failing to Use Exception Handling in Selenium

If you do not use exception handling in Selenium, various negative consequence may originate, compromising the robustness and reliability of your test automation handwriting:

1. Uncaught Errors Halt Execution:Errors (e.g., missing element, timeouts, stale references) get the playscript to ram and terminate dead. This forbid the remaining examination suit from executing, leave in incomplete test footrace and missing flaw.

For example, if an element is missing from the page, a is issued, and the playscript terminates without further action.

2. Lack of Error Reporting:Without exception manipulation, you lose the ability to adequately care and log erroneousness. This makes debug unmanageable because there is no unionised means to collect and account faults, resulting in great time and effort spent diagnose problems.

For example, if a script fails due to an uncaught exception, the want of thorough logging may forbid developer from understanding why the failure occurred.

3. Discrepant Test Results:Tests may react unpredictably if mistake are not command, resulting in inconsistent findings. For example, a test that fails owing to a missing element may legislate when the element reappears, suggesting that there was an intermittent problem.

For example, a examination that look an alert to occur may pass without detecting an subject if the alert does not arrive, but the want of an exception means you miss the fact that anything went wrong.

4. Inability to Handle Dynamic Content:Web page frequently contain dynamic substance, and without exception such as StaleElementReferenceException, you can not effectively manage scenarios in which ingredient change or update. This can lead to unnecessary test failures.

For example, if the DOM updates after identifying an element, the cite becomes moth-eaten (StaleElementReferenceException). Without exception handling, the test fails rather than rehear or relocate the element.

5. Reduced Maintainability:Tests go increasingly difficult to maintain as more hardcoded assumptions are introduced.

For example, presuming that every page load would hap within a certain time limit without accounting for potential timeouts might make scripts brittle. ATimeoutExceptionmay arise if a page guide longer to charge than expect. Without this, you can not construct a retry scheme, resulting in many failures.

Read More:

Can you do error handling without Exception Handling in Selenium?

While it may not be the best approach, you can handle mistake in Selenium without relying directly on exception by using substitute proficiency and access.

Here are some strategies for handling errors in Selenium Python graciously:

1. Implicit Waits

Implicit waiting can help contend situations where constituent are not forthwith available by setting a nonremittal waiting time. This reduces the likelihood of encountering NoSuchElementException when elements are not immediately present.
from selenium signification webdriver

driver = webdriver.Chrome () driver.implicitly_wait (10) # Waits up to 10 seconds for elements to seem

2. Explicit Waits

Explicit waits let you to look for specific conditions to be met before go. This approach can facilitate avoid exceptions related to time issues.

from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome () wait = WebDriverWait (driver, 10) element = wait.until (EC.presence_of_element_located ((By.ID, 'element_id ')))

3. Polling with Retry Logic

Implement canvass mechanisms to control for conditions or element availability without using exception handling directly. This imply creating usage retry logic.

importee clip

from selenium.webdriver.common.by import By def wait_for_element (driver, by, value, timeout=10): end_time = time.time () + timeout while time.time () & lt; end_time: constituent = driver.find_elements (by, value) if component: return component [0] time.sleep (1) return None element = wait_for_element (driver, By.ID, 'element_id ') if element: element.click () else: print (`` Element not found within the timeout period '')

4. Check Element Properties

Before performing actions on elements, control if they are present, visible, and interactable using methods such asis_displayed ().

component = driver.find_element (By.ID, 'element_id ') if element.is_displayed (): element.click () else: print (`` Element is not displayed '')

5. Use Page Object Model (POM)

Encapsulate interactions and checks in page aim. This can centralise error handle logic and make your tests more maintainable.

class LoginPage: def __init__ (self, driver): self.driver = driver self.username_field = (By.ID, 'username ') self.password_field = (By.ID, 'password ') self.login_button = (By.ID, 'login ') def enter_username (self, username): ingredient = self.driver.find_element (* self.username_field) if element.is_displayed (): element.send_keys (username) else: print (`` Username battleground is not displayed '') def enter_password (self, password): element = self.driver.find_element (* self.password_field) if element.is_displayed (): element.send_keys (password) else: print (`` Password field is not displayed '') def click_login (self): element = self.driver.find_element (* self.login_button) if element.is_displayed (): element.click () else: mark (`` Login button is not displayed '')

Read More:

Mutual Exceptions in Selenium WebDriver

When using Selenium WebDriver, you may encounter a few mutual exceptions. These exceptions can happen as a outcome of errors with element location, browser interaction, or timing.

Note:All the examples of Exceptions are in Selenium Python

Below are some of the well-nigh distinctive exclusion in Selenium WebDriver:

1. MoveTargetOutOfBoundsException

MoveTargetOutOfBounds Exception occurs when attempting to interact with an element that is not within the viewable area of the browser. For instance, when the element is site outside the viewable region, often due to scrolling issues.

element = driver.find_element (By.ID, `` element_out_of_view '') actions = ActionChains (driver) actions.move_to_element (element) .perform () # Raises exception if element is out of bounds

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Solution:

To prevent this exception, you can use JavaScript to scroll the element into view before interacting with it. The specific Selenium method where the JavaScript codification should be added is ‘execute_script’.

from selenium import webdriver from selenium.webdriver.common.by importation By from selenium.webdriver.common.action_chains spell ActionChains # Initialize the Chrome WebDriver driver = webdriver.Chrome () # Navigate to the webpage driver.get (`` https: //example.com '') try: # Locate the element that is out of view component = driver.find_element (By.ID, `` element_out_of_view '') # Scroll the constituent into view habituate JavaScript driver.execute_script (`` arguments [0] .scrollIntoView (true); '', element) # Now perform the activeness after insure the ingredient is in view activeness = ActionChains (driver) actions.move_to_element (element) .perform () except MoveTargetOutOfBoundsException as e: print (`` Element is out of bounds: ``, e) eventually: # Close the browser session driver.quit ()

2. InvalidArgumentException

Thrown when an argument pass to a method is invalid. Occurs when incorrect arguments are provided, such as invalid locators or options.

from selenium significance webdriver from selenium.common.exceptions spell InvalidArgumentException driver = webdriver.Chrome () try: # Passing an invalid URL format to the driver driver.get (`` invalid-url '') except InvalidArgumentException as e: print (`` Invalid Argument: ``, e) driver.quit ()

Solution:

A full way to settle this is to:

  • Validate Input: Ensure that the remark provide to WebDriver methods is correct and valid.
  • Use Proper URL Formats: Always pass a aright formatted URL (include http: // or https: //).
url = `` http: //valid-url.com '' if url.startswith (`` http: // '') or url.startswith (`` https: // ''): driver.get (url) else: print (`` Invalid URL format '')

3. UnhandledAlertException

Raised when an unexpected alert is present. Commonly occurs when an alert appears, but the script doesn ’ t handle it, and further actions miscarry.

from selenium meaning webdriver from selenium.common.exceptions spell UnhandledAlertException driver = webdriver.Chrome () driver.get (`` https: //example.com '') # Assuming an alert is spark by some action driver.execute_script (`` alert ('This is an alert '); '') try: # Trying to perform some action without handling the alert driver.find_element_by_id (`` someElement '') .click () except UnhandledAlertException as e: print (`` Unhandled Alert: ``, e) # Handling the alert alert = driver.switch_to.alert alert.accept () driver.quit ()

Solution: 

A good way to resolve this is to:

  • Handle Alerts:Always check for and handle alerts before continue with any other interactions.
  • Use Try-Catch:Encapsulate activity in a try-catch cube and handle alarum if they look.
try: alert = driver.switch_to.alert alert.accept () # or alert.dismiss () if you need to discount it except NoAlertPresentException: print (`` No rattling present '')

4. JavascriptException

Thrown when executing JavaScript through Selenium fails. Occurs when the script provided inexecute_scriptis incorrect or causes an fault in the browser.

from selenium import webdriver from selenium.common.exceptions import JavascriptException driver = webdriver.Chrome () driver.get (`` https: //example.com '') try: # Executing wrong JavaScript driver.execute_script (`` return document.getElementByID ('nonExistentId '); '') except JavascriptException as e: print (`` JavaScript Execution Failed: ``, e) driver.quit ()

Solution:

A good way to resolve this is to:

  • Verify JavaScript Code:Ensure that the JavaScript code you are executing is right and does not contain errors.
  • Test JavaScript Independently:Run the JavaScript code independently in the browser console to check for mistake before using it in Selenium.
try: result = driver.execute_script (`` return document.getElementById ('validId '); '') if event is None: mark (`` Element not found '') except JavascriptException as e: print (`` JavaScript Error: ``, e)

5. NoAlertPresentException

Raised when an expected alert is not present. Happens when trying to interact with an alerting that doesn ’ t exist.

from selenium meaning webdriver from selenium.common.exceptions import NoAlertPresentException driver = webdriver.Chrome () driver.get (`` https: //example.com '') try: # Attempting to trade to an alert that does not survive alert = driver.switch_to.alert alert.accept () except NoAlertPresentException as e: print (`` No Alert Present: ``, e) driver.quit ()

Solution: 

A good way to resolve this is to:

  • Check for Alerts:Always assure if an alarm is present before assay to interact with it.
  • Use Conditional Logic:Use a try-catch block to safely handle cases where no alerting is present.
try: alert = driver.switch_to.alert alert.accept () except NoAlertPresentException: mark (`` No alert to accept '')

Some New Exceptions in Selenium 4.0

Here are some of the new Selenium exceptions:

New Exceptions in Selenium 4.0:

  • ElementClickInterceptedException
  • NoSuchCookieException
  • InvalidCoordinatesException
  • InvalidSessionIdException
  • ElementNotInteractableException

1. ElementClickInterceptedException

is raise when an element you try to tick is not clickable because another element is blocking it.

from selenium signification webdriver from selenium.common.exceptions import ElementClickInterceptedException driver = webdriver.Chrome () driver.get (`` https: //example.com '') try: driver.find_element_by_id (`` blockedElement '') .click () except ElementClickInterceptedException as e: mark (`` Element was blocked by another element: ``, e) # Possible resoluteness: Scroll the element into view or use JavaScript to chatter element = driver.find_element_by_id (`` blockedElement '') driver.execute_script (`` arguments [0] .click (); '', ingredient) driver.quit ()

Solution:

  • Scroll the Element into View:Use JavaScript to scroll the factor into view.
  • Click Using JavaScript:If the element is still blocked, chatter via JavaScript can bypass the issue.

Read More:

2. NoSuchCookieException

Raised when trying to interact with a cooky that doesn ’ t be.

from selenium significance webdriver from selenium.common.exceptions import NoSuchCookieException driver = webdriver.Chrome () driver.get (`` https: //example.com '') try: # Attempting to edit a biscuit that does not exist driver.delete_cookie (`` nonExistentCookie '') except NoSuchCookieException as e: print (`` No such cookie: ``, e) # Possible resolve: Check if the cookie exists before trying to edit it if driver.get_cookie (`` nonExistentCookie '') is None: print (`` Cookie execute not exist '') driver.quit ()

Resolution:

  • Check Before Deleting:Use get_cookie to assure if the cookie exists before trying to blue-pencil or manipulate it.
  • Handle Gracefully:Implement a disengagement or log that the cookie does not survive.

3. InvalidCoordinatesException

Raised when there is an number with the coordinates provided for actions like mouse movements.

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import InvalidCoordinatesException driver = webdriver.Chrome () driver.get (`` https: //example.com '') try: activeness = ActionChains (driver) element = driver.find_element_by_id (`` someElement '') action.move_to_element_with_offset (factor, 10000, 10000) .perform () # Invalid organise except InvalidCoordinatesException as e: print (`` Invalid coordinates provided: ``, e) # Potential resolution: Verify the coordinates before performing the action width, height = element.size ['width '], element.size ['height '] if 0 & lt; = 10000 & lt; width and 0 & lt; = 10000 & lt; height: action.move_to_element_with_offset (component, 10000, 10000) .perform () else: mark (`` Coordinates are out of edge '') driver.quit ()

Resolution:

  • Verify Coordinates:Ensure that the coordinates are within the bounds of the element before try to move to that position.
  • Use Element Size:Use the element ’ s size to validate that the coordinates fall within the element & # 8217; s dimensions.

4. InvalidSessionIdException

Raised when the session ID habituate in a request is invalid or has expired.

from selenium import webdriver from selenium.common.exceptions import InvalidSessionIdException driver = webdriver.Chrome () driver.get (`` https: //example.com '') driver.quit () try: # Attempting to interact after quitting the session driver.find_element_by_id (`` someElement '') .click () except InvalidSessionIdException as e: print (`` Session ID is invalid or expired: ``, e) # Potential resolution: Start a new session driver = webdriver.Chrome () driver.get (`` https: //example.com '')

Resolution:

  • Check Session Status:Ensure that the WebDriver session is still active before get requests.
  • Restart Session:If the session is invalid or expired, start a new WebDriver session.

5. ElementNotInteractableException

is elevate when an element is found but is not interactable (e.g., it ’ s hidden or disable).

from selenium importee webdriver from selenium.common.exceptions import ElementNotInteractableException from selenium.webdriver.common.by import By importee clip # Initialize the Chrome WebDriver driver = webdriver.Chrome () try: # Navigate to the webpage driver.get (`` https: //example.com '') # Attempt to interact with an element (e.g., a hidden or disabled button) constituent = driver.find_element (By.ID, `` hiddenButton '') element.click () omit ElementNotInteractableException as e: print (`` Element is not interactable: ``, e) # Resolution: Wait until the element becomes interactable time.sleep (5) # Wait for 5 seconds (or use WebDriverWait for a dynamical wait) element = driver.find_element (By.ID, `` hiddenButton '') # Try clicking again after waiting if element.is_enabled () and element.is_displayed (): element.click () else: mark (`` Element is still not interactable. '') finally: # Close the browser session driver.quit ()

Resolution

The primary resolution method for anElementNotInteractableExceptionis to ensure that the element is both seeable and enabled before interacting with it.

This can be accomplish using:

  • Explicit Wait:Use WebDriverWait to look until the factor becomes interactable.
  • Time Delay:Introduce a wait (usingtime.sleep ()) to afford the constituent clip to become interactable.

Some Deprecated Selenium Exceptions

Certain elision have been removed or deprecated in newer Selenium versions, most notably Selenium 4. These changes are frequently do to simplify the API, eliminate duplication, or heighten the overall developer experience.

Deprecated Selenium Exceptions:

  • ElementNotVisibleException
  • StaleElementReferenceException
  • InvalidSelectorException
  • InvalidElementStateException
  • WebDriverException

Following are some exceptions that may have been abandoned, make redundant, or deprecated:

1. ElementNotVisibleException

Status: Deprecated in Selenium 3 and eliminate in Selenium 4.

Replaced byElementNotInteractableException. The new exception better captures scenarios in which an constituent exists in the DOM but can not be fudge, such as when it is obscure or disabled.

2. StaleElementReferenceException

Status: While it has not be entirely eliminated, its use has decreased as better practices and creature have been apply to avoid moth-eaten factor concerns. The deprecation is mainly about transferring the focus to improved handling techniques.

Replacement:Developers are urged to utilize WebDriverWait to avoid scenarios that cause this exception.

3. InvalidSelectorException

Status:Deprecated as best validation and more specific exceptions for picker errors have been introduced.

Replacement:This broad elision is no longer required because more descriptive exclusion or built-in validation exist.

4. InvalidElementStateException

Status: Although it is notwithstanding available, its utility is decreasing as Selenium adds more precise exceptions for various phases of element interaction.

Replacement:More distinctive exceptions include ElementClickInterceptedException and ElementNotInteractableException.

5. WebDriverException

Status: This exclusion has not been completely deleted, but its far-flung use is being discouraged in favor of more precise exceptions that provide more information about the exact problem.

Replacement:Use scenario-specific exception for instance TimeoutException, or NoSuchWindowException).

The removal or denigration of these exceptions simplifies the error-handling process and encourages developer to build more robust, and specific code. As Selenium evolve, developers are guide to best practice through these modifications.​

Talk to an Expert

Selenium Resources

Conclusion

Exception handling is a real crucial part of every Selenium Script. Exceptions in Selenium can not be ignored as they disrupt the normal execution of programme. One can write optimal and full-bodied scripts by handling the Exceptions in unique ways. Programmers can care standard exceptions utilize various techniques like Try/catch, Multiple catch blocks, Finally, and others depending upon the requirement of scripts.

LET you run Selenium test on 3500+ real device-browser-OS combinations, ensuring high accuracy and reliable results. With seamless execution on, you can speed up testing and extend more ground. It also offers suave integration to streamline your testing workflow and makes it easier to catch and care exceptions in real-time environments.

Try Exception Handling in Selenium Webdriver

Tags
11,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free