0

I wrote this (joke) code the other day seeing what would happen, but I got some really strange results:

class Foo{
    public static void main(String[] args){
        while(true)
            recur();
    }

    public void recur(){
        while (true){
            try{
                System.out.println("Hi ");
                recur();
            } catch (StackOverflowError e){
                recur();
            }
        }
    }
}

It just continuously prints out "Hi ", with no indication of stopping (I terminated the program after it ran for a full minute). Oddly, sometimes "Hi " gets printed out multiple times on one line (I counted 117 on one line). But, more importantly, the program keeps running, with no termination. Any ideas?

RobotKarel314
  • 417
  • 3
  • 14
  • When it prints a full line, it's because the `StackOverflowError` has been thrown. Why? I don't know. – Yassin Hajaj May 29 '16 at 19:41
  • 2
    This particular example will terminate eventually. It's just that at each level of the stack, a stack overflow error must be thrown twice for the function to complete: once out of the try block and once out of the catch block. "Hi " should be printed approximately 2^(max stack depth) times, which likely takes a lot longer than a minute. – Warren Dew May 29 '16 at 19:51

0 Answers0