Let's say I have a function named foo(). Within foo() there is a try-catch-finally block. Inside the catch block, foo() is called recursively.
My question is:
How can I have the finally block only execute once, on the original function call?
I want to limit the number of recursive calls that can be made by simply using a counter (an Integer that I increment). Please see the example code below and you will have a generic understanding of what I am trying to accomplish:
private Integer recursion_counter = 0;
public ReturnType foo(){
ReturnType returnType = new ReturnType();
try{
// Try to do something...
returnType = doSomething();
} catch (Exception e){
if (recursion_counter == 5) {
// Issue not fixed within 5 retries, throw the error
throw e;
} else {
recursion_counter++;
attemptToFixTheIssue();
returnType = foo();
return returnType;
}
} finally{
resetRecursionCounter();
}
return returnType;
}
private void resetRecursionCounter(){
recursion_counter = 0;
}
Unless I am mistaken, the finally block can potentially be called multiple times, which I do not want to happen.
If you believe there is a better way to accomplish this (e.g., using something other than an incrementing integer, etc.), then please share your thoughts.