Exception Handling in Selenium WebDriver
Related Product On This Page What is Exception?April 24, 2026 · 14 min read · Tool Comparison
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. Why Exception Handling in Selenium in Important? Consequences of Failing to Use Exception Handling in Selenium: Mutual Exceptions in Selenium This guide helps realize and enforce effective exception plow to improve test stability and simplify debugging and maintenance. 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: 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. 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: 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: 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: 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. Explicit waits let you to look for specific conditions to be met before go. This approach can facilitate avoid exceptions related to time issues. Implement canvass mechanisms to control for conditions or element availability without using exception handling directly. This imply creating usage retry logic. importee clip Before performing actions on elements, control if they are present, visible, and interactable using methods such asis_displayed (). Encapsulate interactions and checks in page aim. This can centralise error handle logic and make your tests more maintainable. Read More: 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: 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. 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’. Thrown when an argument pass to a method is invalid. Occurs when incorrect arguments are provided, such as invalid locators or options. Solution: A full way to settle this is to: Raised when an unexpected alert is present. Commonly occurs when an alert appears, but the script doesn ’ t handle it, and further actions miscarry. Solution: A good way to resolve this is to: Thrown when executing JavaScript through Selenium fails. Occurs when the script provided inexecute_scriptis incorrect or causes an fault in the browser. Solution: A good way to resolve this is to: Raised when an expected alert is not present. Happens when trying to interact with an alerting that doesn ’ t exist. Solution: A good way to resolve this is to: Here are some of the new Selenium exceptions: New Exceptions in Selenium 4.0: is raise when an element you try to tick is not clickable because another element is blocking it. Solution: Read More: Raised when trying to interact with a cooky that doesn ’ t be. Resolution: Raised when there is an number with the coordinates provided for actions like mouse movements. Resolution: Raised when the session ID habituate in a request is invalid or has expired. Resolution: is elevate when an element is found but is not interactable (e.g., it ’ s hidden or disable). 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: 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: Following are some exceptions that may have been abandoned, make redundant, or deprecated: 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. 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. 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. 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. 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. 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. On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
Exception Handling in Selenium WebDriver
Overview
What is Exception?
Why is Exception Handling in Selenium Important?
Consequences of Failing to Use Exception Handling in Selenium
Can you do error handling without Exception Handling in Selenium?
1. Implicit Waits
from selenium signification webdriverdriver = webdriver.Chrome () driver.implicitly_wait (10) # Waits up to 10 seconds for elements to seem
2. Explicit Waits
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
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
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)
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 '')
Mutual Exceptions in Selenium WebDriver
1. MoveTargetOutOfBoundsException
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
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
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 ()
url = `` http: //valid-url.com '' if url.startswith (`` http: // '') or url.startswith (`` https: // ''): driver.get (url) else: print (`` Invalid URL format '')
3. UnhandledAlertException
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 ()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
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 ()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
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 ()
try: alert = driver.switch_to.alert alert.accept () except NoAlertPresentException: mark (`` No alert to accept '')
Some New Exceptions in Selenium 4.0
1. ElementClickInterceptedException
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 ()
2. NoSuchCookieException
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 ()
3. InvalidCoordinatesException
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 ()
4. InvalidSessionIdException
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 '')
5. ElementNotInteractableException
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 ()
Some Deprecated Selenium Exceptions
1. ElementNotVisibleException
2. StaleElementReferenceException
3. InvalidSelectorException
4. InvalidElementStateException
5. WebDriverException
Selenium Resources
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously