Selenium C#请尝试/捕获帮助

Selenium C#请尝试/捕获帮助,c#,selenium,automated-tests,C#,Selenium,Automated Tests,我试图在Selenium C中编写一个try/catch,其中如果web元素不存在,则捕获NoSuchElementException,如果元素存在,则抛出一个自定义异常。非常绿色的编码,所以所有的帮助将不胜感激。谢谢 try { IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.

我试图在Selenium C中编写一个try/catch,其中如果web元素不存在,则捕获NoSuchElementException,如果元素存在,则抛出一个自定义异常。非常绿色的编码,所以所有的帮助将不胜感激。谢谢

try
        {
          IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.x-grid-cell-headerId-propertiesColInv.wrappable.icon-spacer.x-unselectable.wrappable.icon-spacer > div > i"));
        }
        catch (NoSuchElementException spIcoNotDisplayed)
        {
            //if spIcon is NOT present; 
            //then continue;
            //else throw custom exception 
        }

好的,我不确定这是否是您想要的,因为您在文本中要求的内容与您的代码不同。此代码捕获所有异常,如果异常是
NoTouchElementException
,它将保持程序运行。否则抛出捕获的异常或自定义异常

try
{
    IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.x-grid-cell-headerId-propertiesColInv.wrappable.icon-spacer.x-unselectable.wrappable.icon-spacer > div > i"));
}
catch(Exception ex)
{
    //Catches every exception
    if(ex is NoSuchElementException)
    {
        //Do nothing, if there's no icon your code will continue as if nothing happened
        //Or throw a custom exception for this case
    }
    else
    {
        //If there's an icon throw the exception
        //Here you can throw a custom exception
        throw ex;
    }
}

当图标存在时,为什么要引发自定义异常?在这种情况下,它将如何进入错误处理程序?当然,如果图标存在,FindElement可以工作并且不会抛出异常。为什么不捕获所有异常,然后在(ex是NoSuchElementException){//Continue;}否则{throw ex;}这两个建议正是我需要的!非常感谢大家!
try
{
    IWebElement spIcon = driver.FindElement(By.CssSelector("#gridview-1080-record-2658335 > td.x-grid-cell.x-grid-td.x-grid-cell-headerId-propertiesColInv.wrappable.icon-spacer.x-unselectable.wrappable.icon-spacer > div > i"));
}
catch(Exception ex)
{
    //Catches every exception
    if(ex is NoSuchElementException)
    {
        //Do nothing, if there's no icon your code will continue as if nothing happened
        //Or throw a custom exception for this case
    }
    else
    {
        //If there's an icon throw the exception
        //Here you can throw a custom exception
        throw ex;
    }
}