The first time the StackOverFlowError
occurs, the call to the last doAnything()
is cancelled and the control is returned to the catch block from the last doAnything()
.
However, because the stack is still practically full, the simple fact of calling System.out.print("y")
will causes another StackOverflowError
because of the need of pushing some value on the stack and then make a call to the function print()
.
Therefore, another StackOverflowError
occurs again and the return is now returned on the catch{} block of the previous doAnything()
; where another StackOverflowError
will happens because the need of stack space required to do a single call to System.out.println("y")
is greater than the amount of space liberated from returning a call from doAnything()
.
Only when there will be enough space on the stack to execute a call to System.out.print("y")
that this process will stop and a catch block will successfully complete. We can see that by running the following piece of code:
public class Principal3b {
static int a = 0;
static int i = 0;
static int j = 0;
public static void main(String[] args) {
System.out.println("X");
doAnything();
System.out.println("Y");
System.out.println(i);
System.out.println(j);
}
private static void doAnything() {
a++;
int b = a;
try {
doAnything();
} catch (final Error e) {
i++;
System.out.println(a);
System.out.println(b);
j++;
}
}
}
Notice that a println(a)
is used instead of a print(a)
; therefore a new line should be printed after each value of a
if everything runs OK.
However, when I run it, I get the following result:
X
62066206620662066206620662066206
6190
Y
17
1
This means that there have been 17 attempts ro run the catch block. Of these catch block executions, 9 are unable to print anything before generating themselves a StackOverflowError; 7 are able to print the value of 6190 but are unable to print a newline after it before themselves rising an error again and finally, there is one that is able to both print the value of 6190 and the newline after it; therefore finally permitting its catch block to complete without any new StackOverflowError and return gracefully up the calls stack.
As we are dealing with StackOverflowError, these numbers are only an example and will vary greatly not only between machines but also between executions and the simple fact of adding or removing any kind of instructions should also change these values. However, the pattern seen here should remains the same.
1yyyyyyyy2
is wrong. it outputs1y2
.the answer is straight forward actually. you are catching the error and suppressing StackOverflow by printing a message. – Debarathtry...finally
and this istry...catch
. – Ale1yyyyyyyyy2
on my system – Karykarylprintln
there is no newline printed! – Aley
s, same as @PremGenError and I cannot debug it because it crashes. – Aley
but the catch block is executed (at least) 29 times. – Ale