Java 如何抛出新的ElementNotFoundException? int btnSize=driver.findElements(By.xpath(“…”).size(); 如果(btnSize>1){ 列表b=driver.findElements(By.xpath(“…”); }如果(btnSize==1),则为else{ WebElement b=driver.findElement(By.xpath(“…”); }否则{ //如何引发异常(例如ElementNotFoundException) //这些变体不起作用? 抛出ElementNotFoundException; 抛出(新元素NotFoundException); 抛出(newelementnotfoundexception(“未找到”); 抛出(newelementnotfoundexception(异常e)); }

Java 如何抛出新的ElementNotFoundException? int btnSize=driver.findElements(By.xpath(“…”).size(); 如果(btnSize>1){ 列表b=driver.findElements(By.xpath(“…”); }如果(btnSize==1),则为else{ WebElement b=driver.findElement(By.xpath(“…”); }否则{ //如何引发异常(例如ElementNotFoundException) //这些变体不起作用? 抛出ElementNotFoundException; 抛出(新元素NotFoundException); 抛出(newelementnotfoundexception(“未找到”); 抛出(newelementnotfoundexception(异常e)); },java,selenium,selenium-webdriver,Java,Selenium,Selenium Webdriver,在抛出新异常时,基本上是通过调用对象的构造函数来创建对象。因此,抛出新元素NotFoundException(“未找到”)或抛出新元素NotFoundException(exception)其中exception是一个异常对象 扔一些可以扔掉的东西 那么,在你的情况下- int btnSize = driver.findElements(By.xpath("...")).size(); if ( btnSize > 1) { List<WebElement> b =

在抛出新异常时,基本上是通过调用对象的构造函数来创建对象。因此,抛出新元素NotFoundException(“未找到”)或
抛出新元素NotFoundException(exception)

其中exception是一个异常对象

扔一些可以扔掉的东西

那么,在你的情况下-

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));
}

关键字new用于创建实例。

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

throw new ElementNotFoundException("Not found!");

抛出新元素NotFoundException(“任意”)NoFoundElementException()对我来说很有用。
if (btnSize > 1)
{
    List<WebElement> b = driver.findElements(By.xpath("..."));
    ...
}
else
{
    WebElement b = driver.findElement(By.xpath("...")); // Might throw an exception
    ...
}
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;