How to Implement a Re-Try-Catch

How do you implement a re-try-catch?

You need to enclose your try-catch inside a while loop like this: -

int count = 0;
int maxTries = 3;
while(true) {
try {
// Some Code
// break out of loop, or return, on success
} catch (SomeException e) {
// handle exception
if (++count == maxTries) throw e;
}
}

I have taken count and maxTries to avoid running into an infinite loop, in case the exception keeps on occurring in your try block.

How to retry after exception?

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.

for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break

Retry on exception in a try catch block

The shortest answer to your question is "just throw a new exception".

But you probably want to be able to test Happy Path too.

Here's what I'd do:

using System;
using System.Threading;

public class Program
{
public static void Main()
{
// what happens when no problem
MyClass.happyPath = true;
MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyMethod(5));

// does the retry work?
MyClass.happyPath = false;
MyClass myClass = new MyClass();
Console.WriteLine(myClass.MyMethod(5));
}
}

public class MyClass
{

public static boolean happyPath = true;

public Test(){}

public string MyMethod(int tryCount) {
while(tryCount > 0)
{
// some logic that returns the switchType
// in this case i'm just manually setting it to 1
int switchType = 1;

try {
switch(switchType)
{
case 1:

if (!happyPath) {
throw new Exception ("Oops, it didn't work!");
}
return "it worked!!!";
case 2:
break;
}
} catch (Exception e){
if (--tryCount == 0) throw new Exception("Failed");
}
}

return null;
}

}

The throw that you add inside the break statement should be caught by your catch which allows you to check out your retry logic. Suggest you add some logging.

How to implement re-try n times in case of exception in C#?

static T TryNTimes<T>(Func<T> func, int times)
{
while (times>0)
{
try
{
return func();
}
catch(Exception e)
{
if (--times <= 0)
throw;
}

}
}

Retry Mechanism catching exception wont work

The ConfirmRequestRetryAsync is an async void method. This means it will return at the first await. The rest of the code will run at some later time, in the same thread context as the caller. So when the exceptions are thrown the retrying method has already returned and there is nothing to catch the exceptions.

The fix is to make it an async Task method, and await this in your retry-method. This might require two variants of the retrying method, one for async methods and one for non-async.

A rule of thumb for async void is to never allow exceptions to be thrown from them, since there is no possibility for anyone to catch them. Always use async Task if exceptions is a possibility.



Related Topics



Leave a reply



Submit