Try/Catch not handling exceptions from Selenium2 FindElement

强颜欢笑 提交于 2019-12-11 02:13:50

问题


I'm playing around with wrapping some Selenium2 API calls in some helper methods, but expected exceptions aren't being handled even though I am catching them. Here's the code:

public static bool IsElementPresent(this IWebDriver driver, By by)
{
    var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
    wait.IgnoreExceptionTypes(new Type[] { typeof(WebDriverException) });
    try
    {
        wait.Until(drvr => drvr.FindElement(by));
        return true;
    }
    catch (NoSuchElementException)
    {
        return false;
    }
    catch (System.TimeoutException)
    {
        return false;
    }
}

In some cases I'm testing against an element that I expect not to be present, so I catch the NoSuchElementException and return false; the calling code looks something like:

bool areYouThere = IsElementPresent(driver, By.CssSelector("li[name=elementThatsNotInTheDom");

The wait.Until(drvr => drvr.FindElement(by)); call stops in the debugger with a "NoSuchElementException was unhandled by user code message", but I'm clearly handling that exception.

This isn't a critical issue because I'm not going to use this pattern in my final solution - I'm mostly just playing around with different ideas and there are better ways of doing this, but I'm very curious as to why this exception is unhandled when I'm clearly handling it.

EDIT

Interestingly enough, even if I add a generic

catch (Exception) {
    return false;
}

to the method it's still uncaught.

EDIT 2

Actually I misspoke above - the generic exception is eventually caught, but when it gets there it's as a WebDriverTimeoutException.

And here's the Aha! moment:

WebDriverWait.Until() only throws WebDriverTimeoutException; the .Net docs are incomplete, but the Ruby docs are slightly more instructive. So what I think is happening is that the lambda is throwing the exception class I expect, and after the appropriate wait period, WebDrierWait.Until() throws the WebDriverTimeoutException. I can confirm this by moving my try/catch block into the lambda, thusly:

wait.Until(drvr => {
    try {
        drvr.FindElement(by);
        return true;
    } catch (OpenQA.Selenium.NotFoundException) {
        return false;
    } catch (System.TimeoutException) {
        return false;
    } catch (Exception) {
        return false;
    }
});

In this situation, the appropriate exception is caught. Mystery solved!


回答1:


This may be a long shot, but the only idea that I have is that maybe there's a name conflict between two NoSuchElementException classes and you're handling the one accessible from your namespace while the code is throwing the other.



来源:https://stackoverflow.com/questions/13990825/try-catch-not-handling-exceptions-from-selenium2-findelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!