Reputation: 110570
I would like to retry calling a function in the exception clause like this:
private int mTries = 0;
private void myFunction() {
try {
// do something
} catch (Exception e) {
if (mTries ++ < MAX_TRIES;
myFunction();
}
}
}
My question, regardless the stack memory usage, calling a function recursively in the catch clause the same as calling it in normal case? I am wonder if doing this will blow off the stack, if my app is running on android platform.
private void anotherFunction(int i) {
if (i == 0)
return;
anotherFunction(i--);
}
Upvotes: 1
Views: 88
Reputation: 30227
My question, regardless the stack memory usage, calling a function recursively in the catch clause the same as calling it in normal case?
Yes, it is exactly the same.
Upvotes: 0
Reputation: 1568
Your second implementation will always cause a stack overlflow. (Try passing in a value even of 1, it will fail).
Upvotes: 0
Reputation: 79838
Why not write it like this?
private void myFunction(){
int triesRemaining = MAX_TRIES;
while( triesRemaining-- > 0 ){
try{
// ... do stuff
return;
}
catch( Exception e ){
}
}
throw new Exception( "too many failures" );
}
However, I seriously recommend you narrow down the catch clause so that you only catch only those types of exception after which you'd want to continue processing.
Upvotes: 5