What does StackOverflowError mean in Java? What is its fix?

帅比萌擦擦* 提交于 2019-12-23 03:33:10

问题


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.



来源:https://stackoverflow.com/questions/18990232/what-does-stackoverflowerror-mean-in-java-what-is-its-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!