如何抛出新的ElementNotFoundException?

时间:2014-02-11 13:36:18

标签: java selenium selenium-webdriver

int btnSize = driver.findElements(By.xpath("...")).size();

if ( btnSize > 1) {
    List<WebElement> b = driver.findElements(By.xpath("..."));
} else if (btnSize == 1){
    WebElement b = driver.findElement(By.xpath("..."));
} else {

    //How do I throw an Exception (e.g. ElementNotFoundException)
    //these variants did not work?

    throw ElementNotFoundException;     
    throw (new ElementNotFoundException);
    throw (new ElementNotFoundException("not found"));
    throw (new ElementNotFoundException(Exception e));
}

3 个答案:

答案 0 :(得分:2)

当抛出一个新的Exception时,基本上你通过调用它的构造函数来创建一个对象。所以它是throw new ElementNotFoundException("not found");或者是throw new ElementNotFoundException(exception),其中例外是一个异常对象;)

答案 1 :(得分:1)

Oracle Reference

抛出someThrowableObject;

所以,在你的情况下 -

throw new ElementNotFoundException("Not found!");

关键字 new 用于创建实例。

答案 2 :(得分:0)

只需在if/else上使用btnSize > 1,如果else btnSize < 1将为您抛出异常:

if (btnSize > 1)
{
    List<WebElement> b = driver.findElements(By.xpath("..."));
    ...
}
else
{
    WebElement b = driver.findElement(By.xpath("...")); // Might throw an exception
    ...
}

PS:你没有指定你在每种情况下使用的xpath,但我觉得在所有三种情况下它都是相同的xpath,并且你只想迭代所有按钮,也许根据按钮数量返回true/false

如果确实如此,那么你可以简单地这样做:

List<WebElement> buttons = driver.findElements(By.xpath("..."));
for (WebElement button : buttons)
{
    button.click(); // or whatever you wanna do with each button...
}
return buttons.size() > 0;