I'm specifically asking what the issues may be with my try/catch
block, which isn't described in the issues linked as "duplicates" to this.
I'm having an issue where I'm trying to catch a StaleElementReferenceException
and then look up the element again but for some reason the exception isn't being caught. I have the method below and when I run the test I get a StaleElementReferenceException
when this line is executed, value = element.GetAttribute(attributeName);
. I assumed (maybe poorly) that adding the check in a try/catch
and specifically looking for the exception would allow me to continue trying until selenium is able to find the element again. The issue is for some reason the exception isn't getting caught and the test immediately exits. Oddly, if I change the catch block to just catch the general Exception
it works just fine. My concern with that is though I could get in a loop that would never exit. I'm using a page object model to initially initialize the elements.
bool isStale = false;
string value = "";
do
{
try
{
value = element.GetAttribute(attributeName);
isStale = false;
}
catch (StaleElementReferenceException)
{
element = driver.FindElement(By.XPath(xPath));
isStale = true;
}
} while (isStale == true);
return value;
This is part of the stack trace:
Test failed with error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.43.600210 (68dcf5eebde37173d4027fa8635e332711d2874a),platform=Windows NT 10.0.17134 x86_64) at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary
2 parameters) at OpenQA.Selenium.Remote.RemoteWebElement.Execute(String commandToExecute, Dictionary
2 parameters) at OpenQA.Selenium.Remote.RemoteWebElement.GetAttribute(String attributeName)