Re-try-catch语句陷入无限循环

时间:2015-07-23 18:40:57

标签: try-catch

我有一段代码包装在try-catch中以捕获异常,但我想重新尝试那段代码,直到它成功为止。我添加了一个基于this post的循环。这就像循环代码一样,但它是一个无限循环。一旦代码成功并移动到下一页,代码仍然循环并最终失败,因为它正在搜索不再可用的定位器,因为页面已经前进到下一页。我的问题是:一旦代码成功,我该如何摆脱循环?

int count = 0;
int maxTries = 1;
while (true)    
{
    try{
        driver.FindElement(By.id("textbox").sendKeys("123");
        driver.FindElement(By.id("submit").click();
        driver.FindElement(By.id("catalog").click();
            if(driver.getTitle().equals("Correct Page"))
        {break;
    }
}
    catch(NoSuchElementException e)
        {
            if (++count == maxTries) throw e;
        }
    }
}

driver.FindElement(By.id("part1").click(); 

1 个答案:

答案 0 :(得分:0)

为此目的使用例外可能不是正确的路线。

而不是while(true),尝试while(!driver.getTitle()。equals(“Correct Page”))

然后在循环内,递增计数,将其与maxTries一起检查,并在超过时断开

相关问题