Re-try-catch 语句陷入死循环

Re-try-catch statement stuck in infinite loop

我有一段代码包裹在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(); 

也许为此目的使用例外不是正确的途径。

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

然后在循环内,递增计数,对照 maxTries 检查并在超过时中断