2014-02-11 21 views
0
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)); 
} 
+1

'拋出新ElementNotFoundException( 「什麼」);' – AntonH

回答

0

Oracle Reference

扔someThrowableObject;

所以,在你的個案

throw new ElementNotFoundException("Not found!"); 

關鍵字被用來創建一個實例。

2

拋出一個新的異常時,基本上你通過調用它的構造函數來創建一個對象。所以這是
throw new ElementNotFoundException("not found");
throw new ElementNotFoundException(exception)
其中的例外是毫無遺漏的,你的異常對象;)

0

剛上btnSize > 1使用if/elseelse會拋出異常爲你,如果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;