Confusing output from infinite recursion within try-catch

前端 未结 7 1981
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 19:13

Consider the following code.

public class Action {
private static int i=1;
public static void main(String[] args)          


        
7条回答
  •  时光说笑
    2020-12-23 19:51

    Note the absence of newline characters in 433943394339. It indicates that something wrong happens inside System.out.println().

    The essential point here is that System.out.println() requires some stack space to work, so that StackOverflowError is thrown from System.out.println().

    Here is your code with marked points:

    public static void main(String[] args) {
        try{
            System.out.println(i); // (1)
            i++;
            main(args); // (2)
        }catch (StackOverflowError e){
            System.out.println(i); // (3)
            i++;
            main(args); // (4)
        }
    }
    

    Let's imagine what happens at level N of recursion when i = 4338:

    • Statement (1) at level N prints 4338. Output 4338\n
    • i is incremented to 4339
    • Control flow enters level N + 1 at (2)
    • Statement (1) at level N + 1 tries to print 4339, but System.out.println() throws a StackOverflowError before it prints a newline. Output 4339
    • StackOverflowError is caught at level N + 1, statement (3) tries to print 4339 and fails for the same reason again. Output 4339
    • Exception is caught at level N. At this point there is more stack space available, therefore statement (3) tries to print 4339 and succeeds (newline is printed correctly). Output 4339\n
    • i is incremented and control flow enters level N + 1 again at (4)

    After this point the situation repeats with 4340.

    I'm not sure why some numbers are printed correclty between sequences without newlines, perhaps its related to internal work of System.out.println() and buffers it uses.

提交回复
热议问题