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

Inf*_*Dev 18 .net c# exception-handling exception

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

对于Eg:

try
{
    //execute some code
}
catch(Exception e)
{
}
Run Code Online (Sandbox Code Playgroud)

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

zie*_*mer 38

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

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

小心避免无限循环.

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


Dav*_*ith 7

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
    }
}
Run Code Online (Sandbox Code Playgroud)


Syn*_*siS 5

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

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

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

int retries = 0;

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

  • 然后,由于没有端点,您也可能遇到stackoverflow. (4认同)