What actually causes a Stack Overflow error? [duplicate]

I’ve looked everywhere and can’t find a solid answer. According to the documentation, Java throws a java.lang.StackOverflowError error under the following circumstance:

Thrown when a stack overflow occurs because an application recurses too deeply.

But this raises two questions:

  • Aren’t there other ways for a stack overflow to occur, not only through recursion?
  • Does the StackOverflowError happen before the JVM actually overflows the stack or after?

To elaborate on the second question:

When Java throws the StackOverflowError, can you safely assume that the stack did not write into the heap? If you shrink the size of the stack or heap in a try/catch on a function that throws a stack overflow, can you continue working? Is this documented anywhere?

Answers I am not looking for:

  • A StackOverflow happens because of bad recursion.
  • A StackOverflow happens when the heap meets the stack.

10 Answers
10

Leave a Comment