Is it possible to execute the code in the try block again after an exception in caught in catch block?

后端 未结 7 831
灰色年华
灰色年华 2021-02-05 06:18

I want to execute the code in the try block again after an exception is caught. Is that possible somehow?

For Eg:

try
{
    //execute some code
}
catch(E         


        
7条回答
  •  一生所求
    2021-02-05 06:46

    If you wrap your block in a method, you can recursively call it

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

    or you could do it in a loop.

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

提交回复
热议问题