Confusing output from infinite recursion within try-catch

前端 未结 7 2012
隐瞒了意图╮
隐瞒了意图╮ 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 20:10

    axtavt Answer is very complete but I'd like to add this:

    As you may know the stack is used to store the memory of variables, based on that you cannot create new variables when you reach the limit, it is true that System.out.println will need some stack resources

    787     public void More ...println(Object x) {
    788         String s = String.valueOf(x);
    789         synchronized (this) {
    790             print(s);
    791             newLine();
    792         }
    793     }
    

    Then after calling the print, the error does not allow you to even call the newLine, it breaks again right on the print. Based on that you can make sure that's the case by changing your code like this:

    public class Action {
        static int i = 1;
    
        public static void main(String[] args) {
            try {
                System.out.print(i + "\n");
                i++;
                main(args);
            } catch (StackOverflowError e) {
                System.out.print(i + " SO " + "\n");
                i++;
                main(args);
            }
        }
    }
    

    Now you will not ask the stack to handle the new lines, you will use the constant "\n" and you may add some debugging to the exception printing line and your output will not have multiple values in the same line:

    10553
    10553 SO
    10553 SO
    10554
    10554 SO
    10554 SO
    10555
    10556
    10557
    10558
    

    And it will keep broken until get some resources to allocate new data and pass to the next i value.

提交回复
热议问题