Paul Mattick
Paul Mattick

Reputation: 3

Terminate function before calling again?

So I have been working on a program in Java. I have a function that runs some code, and when the code throws an exception I want to call it again. Like this:

public void x (String str) {
  try {
    // Initialize
  } catch (SomeException e) {
    System.out.println("Initializing again...");
  }
  try {
    // Do stuffz
  } catch (SomeOtherException e) {
    System.out.println("Trying again...");
    x(str);
  }
}

This works, but it will throw a stack overflow error if it throws the exception too many times. How can I stop the stack overflow error?

Upvotes: 0

Views: 62

Answers (4)

kognise
kognise

Reputation: 632

Maybe you could use a wrapper function, i.e. this:

public void wrapper (String str) {
  while (true) {
    try {
      x(str);
    } catch (SomeException e1) {
      System.out.println("Initializing again...");
      continue;
    } catch (SomeOtherException e2) {
      System.out.println("Trying again...");
      continue;
    }
  }
}

Upvotes: 0

Lino
Lino

Reputation: 19926

Use a loop instead of recursion:

public void x(String str){
    for(;;){ // equal to while(true)
        try {
            // Initialize
        } catch (SomeException e) {
            System.out.println("Initializing again...");
            continue; // returning the loop
        }
        try {
            // Do stuffz
            break; // break out of loop if finished
        } catch (SomeOtherException e) {
            System.out.println("Trying again...");
        }
    }
}

And just break out of that loop once your finished, else it will just loop and loop and loop until your computer dies, the sun explodes or the universe freezes

Upvotes: 1

GiorgosDev
GiorgosDev

Reputation: 1767

The stack overflow happens because you actually don't change anything in parameters that could affect the function to return other result. That means any time you start such a function for parameters which cause the exception it will cause same exception in the inner call. When you are using recursion you should always take care about exit condition. If there's no other good reason, in this case recursion is not a good solution. You should use a loop or add some condition to exit from recursion, it can be number of attempts in your case.

public void x (String str, int attempts) {
if (attempts > 100)
   return;
try {
    // Initialize
} catch (SomeException e) {
    System.out.println("Initializing again...");
    try {
        // Do stuffz
    } catch (SomeOtherException e) {
        System.out.println("Trying again...");
        x(str,attempts+1);
    }
}
}

Upvotes: 0

Gatusko
Gatusko

Reputation: 2598

You are in a infinite recursion if the code go to the second catch. Even if you do stuff to avoid it the risk is very high. I will suggest to make only a second attempt and no more. No one wants a infinte loop of try and catchs.

Upvotes: 0

Related Questions