What does StackOverflowError mean in Java? What is

2019-06-08 10:33发布

问题:

I'm encountering the following error:

Exception in thread "main" java.lang.StackOverflowError
    at Account.draw(Account.java:47)

This is the relevant section of code:

public double draw(double c) {
    if (c > 0) {
        return c;
    } else if (c < 0 && c > AccBalance) {
        AccBalance=-c;
        return AccBalance;
    }

    return draw(c);
}

How can I fix this?

回答1:

In your code, if c == 0, or c <= AccBalance, you keep on recursing the method with the same value of c. So, it will go into an infinite recursion, thus filling up the stack.

For each method invocation, a stack frame is allocated from the stack. Thus your code will end up allocating complete stack memory.

So, for e.g, if you call this method first time with c = 0, this is how the stack grows:

draw(0)
  draw(0)
    draw(0)
      draw(0)
        .. so on

You keep on passing 0 as argument, which doesn't satisfy any of your base cases.

As to how to solve this, we don't really have enough context to find out what should go in place of return draw(c);. But certainly that shouldn't be there. Perhaps return draw(++c);?? But we can only guess.

See also:

  • Recursion: Behind the Scenes


回答2:

You're continually calling the draw() method. So you call the draw() method, then it calls the draw() method, then it calls the draw() method, then it calls the draw() method, et cetera, until you have no more memory left.

Check your return statement at the end. What do you want to return in that case? Right now it just keeps calling draw() again, which is probably not what you want.



回答3:

You have an infinite recursion. StackOverflowError means your call stack got too deep - too many nested functions called without completing any of them - which recursion tends to do.