Selenium - Exception Handling


When we are developing tests, we should ensure that the scripts can continue their execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly.

If an exception occurs due to an element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a logical way rather than terminating the script abruptly.


The actual code should be placed in the try block and the action after exception should be placed in the catch block. Note that the 'finally' block executes regardless of whether the script had thrown an exception or NOT.

try {
   //Perform Action
} catch(ExceptionType1 exp1) {
   //Catch block 1
}  catch(ExceptionType2 exp2) {
   //Catch block 2
} catch(ExceptionType3 exp3) {
   //Catch block 3 
} finally {
   //The finally block always executes.


If an element is not found (due to some reason), we should step out of the function smoothly. So we always need to have a try-catch block if we want to exit smoothly from a function.

public static WebElement lnk_percent_calc(WebDriver driver)throws Exception {
   try {
      element = driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")); 
      return element;
   } catch (Exception e1) {
      // Add a message to your Log File to capture the error
      Logger.error("Link is not found.");
      // Take a screenshot which will be helpful for analysis.
      File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(screenshot, new File("D:\\framework\\screenshots.jpg"));