What is a StackOverflowError in Java? When does this happen?

Can someone tell me what a StackOverflowError is in Java?

+4
source share
5 answers

Stack overflow occurs when too much data is put on stack , which is a limited resource.

Here is an example:

public class Overflow { public static final void main(String[] args) { main(args); } } 

This function calls itself repeatedly without a termination condition. Consequently, the stack is populated because each call must pop the return address on the stack, but the return addresses never pop up from the stack because the function never returns, it just keeps calling itself.

+15
source

There is no such thing as a StackOverFlowException in Java.

There is, however, a class called StackOverflowError and in the documentation :

Thrown when a stack overflow occurs because the application is overloaded too much.

If you donโ€™t know what the stack is, read the following: call stack

+8
source

Each time you call a function, it is allocated a small piece of a special area of โ€‹โ€‹memory - the stack and contains local variables and the context of the function. If our function calls another function, the next part cuts off the stack and so on. The stack is reset when the function returns again. If the nesting level becomes too high, it can overflow.

This is a very general concept. In Java, when the stack size is exceeded, a StackOverflowError . This is a mistake , not an exception , because you are strongly advised to avoid this situation and not recover from it.

A typical example is infinite recursion:

 public void foo(int i) { return foo(i+1); } 
+4
source

Usually when a recursive method is called too many times. For instance:

 public void doSomething(int time) { System.out.println("do #" + (doSomething(time++))); } 
0
source

The Java machine allocates a certain amount of memory to your program. The error was caused by your program using too much memory. The above examples are good, but if you are trying to create a very large array, which can also lead to its overflow. You can allocate more memory (this 200 MB example) for your program using command line arguments

 java -Xmx200m YOUR_PROGRAM_CLASS 

This will reduce the chance of getting a StackOverFlowException.

This explains the command line options

( http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html#Xms )

-1
source

Source: https://habr.com/ru/post/1313071/


All Articles