在catch块中捕获异常后,是否可以再次在try块中执行代码?

问题描述 投票:17回答:7

我想在捕获异常后再次执行try块中的代码。这有可能吗?

对于Eg:

try
{
    //execute some code
}
catch(Exception e)
{
}

如果异常被捕获,我想再次进入try块以“执行一些代码”并再次尝试执行它。

c# .net exception exception-handling
7个回答
36
投票

把它放在一个循环中。可能会在布尔标志周围循环一圈,以控制何时最终要退出。

bool tryAgain = true;
while(tryAgain){
  try{
    // execute some code;
    // Maybe set tryAgain = false;
  }catch(Exception e){
    // Or maybe set tryAgain = false; here, depending upon the exception, or saved details from within the try.
  }
}

小心避免无限循环。

更好的方法可能是将“某些代码”放在自己的方法中,然后可以在try和catch中调用该方法。


5
投票

如果将块包装在方法中,则可以递归调用它

void MyMethod(type arg1, type arg2, int retryNumber = 0)
{
    try
    {
        ...
    }
    catch(Exception e)
    {
        if (retryNumber < maxRetryNumber)
            MyMethod(arg1, arg2, retryNumber+1)
        else
            throw;
    }
}

或者你可以在循环中完成它。

int retries = 0;

while(true)
{
    try
    {
        ...
        break; // exit the loop if code completes
    }
    catch(Exception e)
    {
        if (retries < maxRetries)
            retries++;
        else
            throw;
    }
}

4
投票
int tryTimes = 0;
while (tryTimes < 2) // set retry times you want
{
    try
    {
        // do something with your retry code
        break; // if working properly, break here.
    }
    catch
    {
        // do nothing and just retry
    }
    finally
    {
        tryTimes++; // ensure whether exception or not, retry time++ here
    }
}


1
投票

还有另一种方法可以做到这一点(尽管正如其他人提到的那样,并不是真的推荐)。下面是一个使用文件下载重试的示例,以更紧密地匹配VB6中Ruby中的retry关键字。

RetryLabel:

try
{
    downloadMgr.DownLoadFile("file:///server/file", "c:\\file");
    Console.WriteLine("File successfully downloaded");
}
catch (NetworkException ex)
{
    if (ex.OkToRetry)
        goto RetryLabel;
}

1
投票

ole goto有什么问题?

 Start:
            try
            {
                //try this
            }
            catch (Exception)
            {

                Thread.Sleep(1000);
                goto Start;
            }

0
投票

这应该工作:

count = 0;
while (!done) {
  try{
    //execute some code;
    done = true;
  }
  catch(Exception e){
  // code
  count++;
  if (count > 1) { done = true; }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.