Handling Exceptions in Selenium Test Scripts
Handling Exceptions in Selenium Test Scripts
When writing test scripts using Selenium (a popular tool for automating web browsers), errors or exceptions can occur due to many reasons—like elements not found, timeouts, or browser issues. Handling these exceptions properly ensures your tests are more reliable and can recover gracefully instead of just crashing.
What is an Exception?
An exception is an error that happens during the execution of a program. If not handled, it will stop your test immediately.
Common Selenium Exceptions
NoSuchElementException: Element not found on the page.
TimeoutException: Waiting for an element or condition timed out.
ElementNotInteractableException: Element is present but cannot be interacted with.
StaleElementReferenceException: Element is no longer attached to the DOM.
How to Handle Exceptions in Selenium
You use try-except blocks (in Python) or try-catch blocks (in Java) to catch exceptions and decide what to do next.
Example in Python (Selenium with try-except)
python
Copy
Edit
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
element = driver.find_element("id", "submit-button")
element.click()
except NoSuchElementException:
print("Error: The submit button was not found on the page.")
except TimeoutException:
print("Error: Loading the page took too long.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
driver.quit()
The try block contains the code that might throw exceptions.
The except blocks handle specific exceptions.
The finally block runs no matter what, often used to close the browser.
Benefits of Handling Exceptions
Prevent test crashes.
Log useful error messages.
Take screenshots or save logs when errors happen.
Retry actions or clean up resources after failure.
Learn Selenium JAVA Course in Hyderabad
Read More
Using Loops and Conditions to Control Test Flow
⚙️ Java + Selenium Programming Concepts
Running Tests with TestNG XML Suite
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment