top of page
priyankadube2012

Exception Handling in Selenium/Java

Most Common Selenium Exceptions and How to Handle Them :

 

When working with Selenium WebDriver for test automation, you'll inevitably encounter exceptions.


What is an Exception?

These are unexpected events that disrupt the normal flow of your script's execution. Understanding and handling exceptions effectively is crucial for writing robust and reliable Selenium tests.

 


 

 

Types of Exceptions:

 

There are two main types of exceptions in Java:

 

    Checked Exceptions: These exceptions are checked by the compiler during compilation. The compiler will raise an error if a checked exception is not handled using a try-catch block or declared using the throws keyword in the method signature. Examples of checked exceptions include IOException, FileNotFoundException, and SQLException.

 

    Unchecked Exceptions: These exceptions occur during the runtime execution of your program. The compiler does not force you to handle them, but it's generally considered good practice to do so for robust code. Unchecked exceptions typically represent programming errors or unexpected conditions, such as NullPointerException, IndexOutOfBoundsException, and ArithmeticException.

 

 

Hierarchy of Exception:

 


Exception vs. Error: Handling Program Issues


Both exceptions and errors are subclasses of the Throwable class in Java, but they represent different types of problems:


  • Errors: These are severe issues that typically indicate a problem outside your program's control. They often signal resource exhaustion (e.g., out of memory) or system malfunctions. Recovering from errors is usually difficult, and your program may need to terminate abnormally.

  • Exceptions: These are unexpected events that occur during program execution but can potentially be handled within your code. They often represent programming errors (e.g., null pointer exceptions) or issues related to user input or external interactions. By using try-catch blocks or other exception handling mechanisms, you can gracefully recover from exceptions and prevent your program from crashing.

In essence, errors are like major system failures, while exceptions are like bumps in the road that your program can potentially navigate around. 

 

 

Exception Handling in Selenium


What is exception handling?


 

  • Exception handling is a robust mechanism in programming that allows you to gracefully deal with unexpected events, or errors, that may arise during the runtime execution of your program. These errors can stem from various sources, including: By implementing exception handling techniques, you can prevent your program from abruptly terminating and instead take appropriate actions to handle the error. This can involve: Effective exception handling is crucial for writing reliable and user-friendly software. It ensures your program doesn't crash unexpectedly and provides a smoother experience for the user.

  • Programmer errors (e.g., attempting to divide by zero)

  • Hardware failures (e.g., disk errors)

  • External resource issues (e.g., file not found, network connection problems)

  • Resource exhaustion (e.g., running out of memory)



There are three main ways to handle exceptions in Selenium:

 

  1.  Try-Catch Blocks: The try-catch block is the most common way to handle exceptions. You enclose the code that might throw an exception within a try block. Then, you use one or more catch blocks to specify the types of exceptions you want to handle. If an exception occurs in the try block, the execution jumps to the corresponding catch block that matches the exception type. You can have multiple catch blocks for a single try block, each handling a specific type of exception.

 

 

  

      2.     Try-Catch-Finally Blocks: The try-catch-finally block builds upon the try-catch approach by adding a finally block. The finally block always executes, regardless of whether an exception occurs in the try block or not. This is typically used to run cleanup code, such as closing resources or logging messages, even if an exception disrupts the normal flow.

 

 

   3.   Throw Keyword: The throw keyword is used to explicitly throw an exception from a method. This allows you to signal an exceptional condition to the caller of the method. However, it's generally recommended to handle exceptions within the method where they occur whenever possible, as throwing exceptions can make your code harder to follow and debug. Only throw exceptions for conditions that cannot be handled within the current method's scope. Remember that only objects of the Throwable class or its subclasses can be thrown.

 


 

Selenium Exceptions

 

There are several common exceptions you might encounter while working with Selenium WebDriver.

 

1. Not Found Exceptions (Several Types):

 

  •     NoSuchWindowException: This exception occurs when WebDriver tries to switch to a window that doesn't exist or is unavailable.

  •     NoSuchFrameException: Similar to NoSuchWindowException, this happens when WebDriver attempts to switch to a frame that doesn't exist on the page.

  •     NoSuchElementException: This is a frequent exception thrown when WebDriver is unable to locate an element using your chosen locator (e.g., ID, name, CSS selector, XPath). This means the findElement method cannot find the specified element on the web page.

  •     NoAlertPresentException: This exception is thrown when WebDriver tries to switch to an alert that isn't present on the page.

 

 

 Above code throws NoSuchElementException

 

2. Timeout Exception:

 

This exception occurs when a Selenium command doesn't complete within the specified timeframe. For example, if you set an implicit wait for 10 seconds and an explicit wait for 5 seconds, and the page doesn't load within that combined time, you'll encounter a Timeout Exception.

 

3. StaleElementReferenceException:

 

This exception indicates that the element you're referencing is no longer present on the Document Object Model (DOM) of the page. This could happen because the element belongs to a different frame, the user navigated away, the DOM refreshed, or a frame or window was switched.

 

4. InvalidElementState Exceptions (Two Types):

 

    ElementNotVisibleException: Even though the element exists in the DOM, it might not be visible (meaning you can't interact with it). This exception is thrown when you try to perform an action on an invisible element.

    ElementNotSelectableException: This exception occurs when an element is present in the DOM but is disabled (cannot be clicked or selected).

 

5. SessionNotFoundException:

 

This exception is thrown when you try to interact with WebDriver immediately after quitting the browser session. WebDriver needs an active browser session to perform actions.

 

 Hope this provides you a quick overview of exception and its handling in Java/Selenium. Happy Learning !

 

 

 

 

 

 

 

 

 

32 views

Recent Posts

See All
bottom of page