michael
michael

Reputation: 110570

Recursively calling a function in the exception clause

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

Answers (3)

Luis Casillas
Luis Casillas

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

Saish
Saish

Reputation: 1568

Your second implementation will always cause a stack overlflow. (Try passing in a value even of 1, it will fail).

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

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

Related Questions