I was wondering what happens when you try to catch an StackOverflowError and came up with the following method:
class RandomNumberGenerator {
static int
main recurses on itself until it overflows the stack at recursion depth R.R-1 is run.R-1 evaluates cnt++.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.println requires stack space, a new stack overflow is triggered at depth R-1 instead of depth R.R-2.R-3.R-4.R-5.println to complete (note that this is an implementation detail, it may vary).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.main completed successfully at depth R-5, the whole stack unwinds without more catch blocks being run and the program completes.