I have a regular, non-static sendMail method which may occasionally fail. I need to catch any errors and retry the method N number of times. I'm not sure I'm doing the right thing, and there's also a compilation error:
public void sendMail(List<String> params) {
try {
//...
static int retrycount = 0; // static not allowed here (but need to keep static var for recursion)
int maxretries = 3;
}
catch (Exception e) {
log.info(e);
// Recursion to retry
sendMail(params);
retrycount++;
}
}
First of all, is recursion from a try/catch block correct? Also, is there a better way to do this?
I can't make the sendMail method static, there are too many references to it in the existing code.
Your retry will never work in the first place because inside every try block you are setting retrycount to 0.
You'd probably be better off throwing the exception instead of catching it. Then using some kind of a while loop till it completes, maybe with a configurable delay between retries. Or if you're using Spring there is the Retryable annotation.
void someMethod(){
int attempts = 0;
while(attemps <= 3){
try {
sendMail(...);
break;
} catch (Exception e){
attempts++;
// Log failed to send mail or something meaningful, maybe add a delay here?
}
}
}
This solution is much cleaner than using recursion as if you wanted to retry many times, eventually you'd get a stack overflow error. It also keeps the responsbility of the sendMail function simple, and avoids adding complicated retry logic to an otherwise simple method.
Also, if you end up having to make other methods retryable in the same fashion then it would be much easier to abstract away the retry logic into some kind of executor service that handles it all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With