I have to make a function call. If it fails, I retry another 2 times. If it still fails after the 2 retrys, I throw an exception.
Below is my current code which is working:
for (int retry = 0; retry < 4; retry++) {
try {
callFunction();
break;
} catch (Exception e) {
if (retry >= 0 && retry < 3) {
warn("callFunction failed. Retrying.." +(retry+1));
} else {
warn("Retried maximum number of "+(retry+1)+" times. Failing the script");
e.printStackTrace();
}
}
}
OUTPUT:
callFunction failed. Retrying..1
callFunction failed. Retrying..2
callFunction failed. Retrying..3
Retried maximum number of 4 times. Failing the script
I understand that this is not the most efficient way to code even though it is working. Can you help me refactor this code to meet the best practice standards of Java clean code?
What's not so great here:
retry >= 0
condition(retry + 1)
I think a while
loop might flow more naturally here,
and checking at the end the retry count.
int maxRetries = 3;
int retry = 0;
Exception thrown = null;
while (retry < maxRetries) {
try {
callFunction();
break;
} catch (Exception e) {
thrown = e;
retry++;
warn("callFunction failed. Retrying.." + retry);
}
}
if (retry == maxRetries) {
warn("reached max");
thrown.printStackTrace();
}
Actually, it's even better if you turn this into a function. There will be fewer variables:
void executeWithRetries(int maxRetries) {
Exception thrown = null;
for (int retry = 0; retry < maxRetries; retry++) {
try {
callFunction();
return;
} catch (Exception e) {
thrown = e;
warn("callFunction failed. Retrying.." + retry);
}
}
warn("reached max");
thrown.printStackTrace();
}