Infinite recursive function


I have an infinite recursive cycle in Java

public  void infiniteLoop(Long x){

    infiniteLoop(x + 1);

public static void main(String[] args) {

    StackOverFlow st = new StackOverFlow();

In this snippet of code that shows a StackOverFlow error as expected, but if I look at the output of the console the error is shown in several lines:

My question is, why does this happen? Should not it stop as soon as the first stack overflow error is displayed?

asked by Sebastian Leandro 10.04.2017 в 17:34

1 answer


The problem is in the output stream of the application. I imagine that your output is printed in System.out while the output of the errors is being sent to System.err . Being two different streams, the writing is not sequential. Then, consider that each of these streams must flushe the output to the same console, and again, it is not sequential, so the output looks strange.

To solve these problems, I recommend:

  • Use a single output stream. To do this, instead of using error.printStackTrace() (which in your case is used automatically) you could use error.printStackTrace(System.out) .

  • Use a logging system such as log4j2 or logback. These frameworks contain the logic to redirect the output evenly to a single output stream.

  • answered by 10.04.2017 / 17:47