【问题标题】:A try-catch block within a for-loop, first attempt exception goes to catch block, then continues to next loop iteration, second doesn'tfor循环中的try-catch块,第一次尝试异常进入catch块,然后继续下一个循环迭代,第二个不
【发布时间】:2019-06-14 20:04:37
【问题描述】:

for 循环中的 Try-catch 块。第一次尝试,异常进入循环内的 catch 块,在 catch 块内继续将其抛出回循环的开头。但是第二次在 try 块中遇到异常时,它会在调用方法时抛出 try-catch 块,而不是停留在循环中

for (int count = 0; count < listCount; count++)
{
    try
    {
        var selectElement   = new SelectElement(pageElement);
        selectElement.SelectByText(pagevalue);
        break;
    }
    catch (NoSuchElementException NSE)
    {

   driver.FindElement(By.Id("policyNumber")).SendKeys(policies[count]);
        driver.FindElement(By.Id("btnOK")).Click();
        continue;
    }   
}

希望异常总是在方法内的 try-catch 块内捕获,而不是跳出到方法外的 try-catch。

【问题讨论】:

  • 可能抛出的异常不是NoSuchElementException异常
  • 你是对的。没注意到。该元素已经过时并引发了不同的异常。谢谢 dcg

标签: c# for-loop try-catch


【解决方案1】:

你应该在最后添加另一个catch,以捕获所有你没有考虑到的Exception

for 循环中的 Try-catch 块。第一次尝试,异常进入循环内的 catch 块,在 catch 块内继续将其抛出回循环的开头。但是第二次在 try 块中遇到异常时,它会在调用方法时抛出 try-catch 块,而不是停留在循环中

for (int count = 0; count < listCount; count++)
{
    try
    {
        var selectElement   = new SelectElement(pageElement);
        selectElement.SelectByText(pagevalue);
        break;
    }
    catch (NoSuchElementException NSE)
    {

   driver.FindElement(By.Id("policyNumber")).SendKeys(policies[count]);
        driver.FindElement(By.Id("btnOK")).Click();
        continue;
    }  
    catch (Exception ex)
    {
       //Do something with other exception
    }  
}

【讨论】:

    【解决方案2】:

    第二个异常与 catch 块中指定的异常类型不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多