1

Is it good practice to use Try and Catch when doing selenium testing? I am using a try/catch through out my test cases to fix some Exception that appear when testing, is that the best approach?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

3 Answers3

1

Exceptions

Exceptions may occur while executing your Selenium related test framework due to coding errors, errors due to wrong input or other unforeseeable things. Hence it is always a best practive to surround the suspected code block within a blobk.


try and catch

Details:

  • try: The lines of code within the try block is used to enclose the code that might throw an exception. If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

  • catch: The lines of code within the catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception can be either the parent class exception ( i.e., Exception) or the generated exception type. A good approach is to declare the generated type of exception.

Note: The catch block must be used after the try block only. You can use multiple catch block with a single try block.


An example

A demonstration of the usage of try-catch:

try{
    if(driver.findElement(By.xpath("xpath_of_the_desired_element")).isDisplayed())
    System.out.println("Element is present and displayed");
    else
    System.out.println("Element is present but not displayed"); 
}catch (NoSuchElementException e) {
    System.out.println("Element is not present, hence not displayed as well");
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

Yes, Try catch use always a good practice. But Sometime it depends on programming and logic. But in general perspective Try/Catch is very important for data scraping using Selenium.

0

It is a normal practice. One of the example of such practice you can find in org.openqa.selenium.support.ui.FluentWait of Selenium itself where until(..) function catches all the exceptions and then re-throw the ones not mentioned through ignoring(..) or ignoreAll(..) methods.

However it is better not to use it often since making use the exceptions to design your flow-control is considered an anti-pattern.

Alexey R.
  • 8,057
  • 2
  • 11
  • 27