Can not catch NoSuchElementException with PageFactory (Selenium WebDriver)



  • My question is like Problem catching Selenium Webdriver NoSuchElementException but there is no answer to resolve an issue.

    Class SmallLoginLocators:

    public class SmallLoginLocators {
        public final String PASSWORD1 = "__nothing";
        public final String PASSWORD2 = "password";
        @FindBy (name = PASSWORD1)    public WebElement passwordField1;
        @FindBy (name = PASSWORD2)
        public WebElement passwordField2;
    }
    

    There is password text field with different locators on two pages. Test can start from any of these pages. So I try to access that webelement:

    public WebElement getPasswordField() {
        SmallLoginLocators slogin = PageFactory.initElements(wd, SmallLoginLocators.class);
        WebElement password;
        try {
            password = slogin.passwordField1;
        } catch (NoSuchElementException e) {
            password = slogin.passwordField2;
        }
        return password;
    }
    

    getPasswordField() returnes NoSuchElementException on line

    password = slogin.passwordField1;
    

    BUT!!! that is not handled by catch (NoSuchElementException e).

    Q1: Why?

    Q2: How to resolve?

    Note: NoSuchElementException I get is from org.openqa.selenium.NoSuchElementException and imports are valid. I suspectthat the issue is in PageFactory.initElements source, but my junior knowledge of java has not given me any chance to understand.



  • My answer is not directly to your question. It is advice. You should not use try catch for logic realization. Program languages (Java, c#, python etc) have if ... else statements. And you can use them for your problem.

    not debugged code, simply for example

    if(slogin.passwordField1.Existed)
    { 
      return slogin.passwordField1;
    } 
    else 
    {
      return slogin.passwordField2;
    }
    

    You can find how realize existed property in Internet (it is easy) and you will levelup you developer skills


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2