Confusing output from infinite recursion within try-catch

前端 未结 7 1980
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 19:13

Consider the following code.

public class Action {
private static int i=1;
public static void main(String[] args)          


        
相关标签:
7条回答
  • 2020-12-23 20:11

    The bottom line is that StackOverflowError is an error, not an exception. You are handling an error, not an exception.So the program has already crashed when it enters the catch block.Regarding the strange behaviour of the program, below is the explanation on basis of java buffers from this official doc:

    For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format

    The System.out.println() internally calls the PrintStream which is buffered. You don't loose any data from the buffer, it gets all written to the output( terminal in your case) after it fills up, or when you explicitly call flush on it.

    Coming back to this scenario, it depends on the internal dynamics of how much the stack is filled up and how many print statements were able to get executed from the catch in main() and those number of characters were written to the buffer. Here after the first try is executed, i.e. in the event of first occurence of the stack overflow, the first System.out.println() fails to print the new line so it flushed the buffer with remaining characters.

    0 讨论(0)
提交回复
热议问题