Search code examples
c#.netexception

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


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.


Solution

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