Confusing output from infinite recursion within try-catch

前端 未结 7 2011
隐瞒了意图╮
隐瞒了意图╮ 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 19:55

    According to my test:

    When Exception is thrown by try Block, i has same value when it comes in catch block (as its not incremented due to exception)

    and then inside catch block same exception is thrown and which is again caught by catch block !

    I tried Following Code

    try {
                System.out.println("Try " + i);
                i++;
                main(args);
            } catch (StackOverflowError e) {
                System.out.println("\nBefore");
                System.out.println("Catch " + i);
                i++;
                System.out.println("After");
                main(args);
                
            }
    

    Output :

    Try 28343
    Try 28344
    Before
    Before
    Before
    Before
    Catch 28344
    After
    Try 28345
    Try 28346
    Try 28347
    Try 28348
    Before
    Before
    Before
    Before
    Catch 28348
    After
    Try 28349
    

    when try block throws exception it is caught by catch block but when it goes to System.out.println("Catch " + i); again Exception is thrown 4 times (in my eclipse) Without printing System.out.println("Catch " + i);

    As in above output, i have tested it by printing "Before" Text which is printed four times before it prints System.out.println("Catch " + i);

提交回复
热议问题