24

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(Exception e)
{
}

If the exception is caught I want to go in the try block again to "execute some code" and try again to execute it.

5

9 Answers 9

47

Put it in a loop. Possibly a while loop around a boolean flag to control when you finally want to exit.

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.
  }
}

Just be careful to avoid an infinite loop.

A better approach may be to put your "some code" within its own method, then you could call the method from both within the try and the catch as appropriate.

9

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;
    }
}
2
  • 4
    And then you can also run into stackoverflow due to no endpoint. Apr 16, 2012 at 9:51
  • What if that function returns some value instead of void? Oct 21, 2019 at 12:40
8
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
    }
}
2
  • What if I want to throw an Exception if the 2nd try fails? Should I need another catch block for that? Would appreciate if you can share the syntax.
    – Heike
    Mar 20, 2019 at 15:47
  • If you want throw exception, it may be easy. just write in catch (Exception ex) { if (tryTimes == 2) throw ex; } Mar 22, 2019 at 16:06
4

already answered in these (and other) links

Better way to write retry logic without goto

Cleanest way to write retry logic?

How can I improve this exception retry scenario?

2

There is another way to do it (though as others have mentioned, not really recommended). Here's an example using a file download retry to more closely match the retry keyword found in Ruby in VB6.

RetryLabel:

try
{
    downloadMgr.DownLoadFile("file:///server/file", "c:\\file");
    Console.WriteLine("File successfully downloaded");
}
catch (NetworkException ex)
{
    if (ex.OkToRetry)
        goto RetryLabel;
}
3
  • 3
    Seems a lot more clear than recursion or infinite loops to solve this particular problem.
    – Bill
    Feb 14, 2012 at 5:36
  • 1
    Unfortunately, that's exactly what you potentially accomplished here - an infinite loop. If the exception occurs, and nothing is done to resolve the underlying cause, there is no retry counter or such to stop the loop. The ex.OkToRetry check might be a start to this, but it isn't clear as to if or where this would ever be set differently between true and false.
    – ziesemer
    May 20, 2013 at 20:45
  • 3
    @ziesemer - the same could be said for your example which got accepted as the answer. Feb 25, 2014 at 12:16
1

I know the community opinion about goto, but this is a case where I would (and do) use it. One of my applications runs a BackgroundWorker which populates an ObservableCollection. While the BackgroundWorker is running and the ObservableCollection is being populated, I allow some other functionality through the UI, but I needed to base some logic on the count of the ObservableCollection at a point in time. So I did this:

long resultCount;           
try_again:
try
{
    //This statement sometimes fails because ocResultList is volatile
    //while the BackgroundWorker is running

    resultCount = <ClassName>.ocResultList.LongCount();
}
catch
{
    goto try_again;
}

if(resultCount...)
{
    //do something
}

Does exactly what I want - and no spaghetti code

1
  • Welcome to Stack Overflow! This answer doesn't seem different enough from the other proposed goto solutions already provided. Including an answer with a unique change for your situation that doesn't apply to the question is generally not helpful to others.
    – siva.k
    Aug 28, 2021 at 4:49
0

This should work:

count = 0;
while (!done) {
  try{
    //execute some code;
    done = true;
  }
  catch(Exception e){
  // code
  count++;
  if (count > 1) { done = true; }
  }
}
1
  • why use flags, you are running a for loop here. so use a for loop structure. Apr 16, 2012 at 9:52
0

What's wrong with the ole goto?

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

                Thread.Sleep(1000);
                goto Start;
            }
3
  • because they lead to spaghetti code. See stackoverflow.com/questions/3517726/… Jun 25, 2018 at 19:15
  • @Malky.Kid, any code leads to spaghetti code if you don't refactor. Having a goto statement in one place is fine, and may actually cleanup your code.. Jun 25, 2018 at 19:18
  • @Malky.Kid you link reinforces my answer. "goto's are appropriate in a few places, such as for jumping out of nested loops" Jun 28, 2018 at 2:38
0

Try this:

try {  
  for (var i=0; (i < t && condition) || i === 0; i++) {
    //t is how many times you want the code to run.
    //condition should be true when there is an error.
    //The code you want to execute multiple times if it fails.
  }
} catch (e) {
  
  //The code you want to execute if the code still runs into an error after being repeated multiple times.
  
}

So, the code will run at least once. The condition should be true when the code results in an error, so the code will keep running until i = t, or the condition is false. If you want to execute some code after the first error, you can use if (i > 0), or if (i === 1) to do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.