Why does this method print 4?

前端 未结 7 1650
抹茶落季
抹茶落季 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 14:03

    I think the number displayed is the number of time the System.out.println call throws the Stackoverflow exception.

    It probably depend on the implementation of the println and the number of stacking call it is made in it.

    As an illustration:

    The main() call trigger the Stackoverflow exception at call i. The i-1 call of main catch the exception and call println which trigger a second Stackoverflow. cnt get increment to 1. The i-2 call of main catch now the exception and call println. In println a method is called triggering a 3rd exception. cnt get increment to 2. this continue until println can make all its needed call and finally display the value of cnt.

    This is then dependent of the actual implementation of println.

    For the JDK7 either it detect cycling call and throws the exception earlier either it keep some stack resource and throw the exception before reaching the limit to give some room for remediation logic either the println implementation doesn't make calls either the ++ operation is done after the println call thus is by pass by the exception.

提交回复
热议问题