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
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
}
}
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;
}
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.
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;
}
}
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?
What's wrong with the ole goto
?
Start:
try
{
//try this
}
catch (Exception)
{
Thread.Sleep(1000);
goto Start;
}