First, you have a catch
clause which doesn’t catch Error
s:
catch(Exception e){
System.out.println("Catch");
}
Since Error
s are not Exception
s, this does not catch StackOverflowError
s and the print statement will not get executed. If an Error
is not catched, it’s stack trace will get printed by the default handler of a thread, if it ever reaches that point. But you have another clause:
finally{
SimpleFile.main(args);
}
The code of the finally
clause will always get executed when the try
block completes, whether normally or exceptionally. Since your try
block contains an infinite recursion, it will never complete normally.
In the exceptional case, i.e. when a StackOverflowError
is thrown, the finally
action will go into into an infinite recursion again, which may again eventually fail with a StackOverflowError
, but since it bears the same finally
block, it will also go into the infinite recursion again.
Your program is basically saying “perform an infinite recursion, then another infinite recursion”. Note that you can’t distinguish from the printing of "main"
whether the program runs in the primary infinite recursion or one triggered from a finally
block (except that line breaks might be missing if a stackoverflow happens right in between the println
execution).
So if we assume that a particular JVM has a limit of 1000
nested invocations, your program will perform 2¹⁰⁰⁰
invocations of your main
method (quantification). Since your main
method actually does nothing, an optimizer could elide even this incredible number of invocations, but this optimization also implies that the required stack size vanishes and thus, an even higher number of recursive invocations becomes possible. Only a JVM implementation enforcing an intentional limit on the supported number of recursive invocations, independent from the actually required stack space, could enforce this program to ever terminate.
But note, that in the case of an infinite recursion, there is no guaranty to get a StackOverflowError
at all. Theoretically, a JVM having an infinite stack space would be a valid implementation. This implies that a JVM, practically optimizing recursive code to run without requiring additional stack space, would be valid too.
So for a typical implementation like Oracle’s JVM, it is practically impossible for your program to ever report a StackOverflowError
. They happen, but are shadowed by your follow-up recursions in the finally
block, thus are never reported.