Why does this method print 4?

前端 未结 7 1648
抹茶落季
抹茶落季 2020-12-12 13:18

I was wondering what happens when you try to catch an StackOverflowError and came up with the following method:

class RandomNumberGenerator {

    static int         


        
7条回答
  •  悲哀的现实
    2020-12-12 13:44

    1. main recurses on itself until it overflows the stack at recursion depth R.
    2. The catch block at recursion depth R-1 is run.
    3. The catch block at recursion depth R-1 evaluates cnt++.
    4. The catch block at depth R-1 calls println, placing cnt's old value on the stack. println will internally call other methods and uses local variables and things. All these processes require stack space.
    5. Because the stack was already grazing the limit, and calling/executing println requires stack space, a new stack overflow is triggered at depth R-1 instead of depth R.
    6. Steps 2-5 happen again, but at recursion depth R-2.
    7. Steps 2-5 happen again, but at recursion depth R-3.
    8. Steps 2-5 happen again, but at recursion depth R-4.
    9. Steps 2-4 happen again, but at recursion depth R-5.
    10. It so happens that there is enough stack space now for println to complete (note that this is an implementation detail, it may vary).
    11. cnt was post-incremented at depths R-1, R-2, R-3, R-4, and finally at R-5. The fifth post-increment returned four, which is what was printed.
    12. With main completed successfully at depth R-5, the whole stack unwinds without more catch blocks being run and the program completes.

提交回复
热议问题