Try-catch-finally order of execution appears to be random [duplicate]

[亡魂溺海] 提交于 2019-12-05 12:09:48

问题


I am trying to understand how the try-catch-finally execution flow works. There are a couple of solutions from Stack Overflow users regarding their execution flow.

One such example is:

try {
    // ... some code: A
} 
catch(...) {
    // ... exception code: B
} 
finally {
    // finally code: C
}

Code A is going to be executed. If all goes well (i.e. no exceptions get thrown while A is executing), it is going to go to finally, so code C is going to be executed. If an exception is thrown while A is executed, then it will go to B and then finally to C.

However, I got different execution flows when I tried it:

try {
    int a=4;
    int b=0;
    int c=a/b;
}
catch (Exception ex)
{
    ex.printStackTrace();
}
finally {
    System.out.println("common");
}

I am getting two different outputs:

First output:

java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
lication.AppMain.main(AppMain.java:140)
common

However, when I ran the same program for the second time:

Second output:

 common
    java.lang.ArithmeticException: / by zero
    at substrings.main(substrings.java:15)

What should I conclude from this? Is it going to be random?


回答1:


printStackTrace() outputs to standard error. System.out.println("common") outputs to standard output. Both of them are routed to the same console, but the order in which they appear on that console is not necessarily the order in which they were executed.

If you write to the same stream in both catch block and finally block (for example, try System.err.println("common")), you'll see that the catch block is always executed before the finally block when an exception is caught.




回答2:


Exception's printstacktrace() method source code(defined in Throwable class)

public void printStackTrace() {
        printStackTrace(System.err);
    }

The formatting of output occurs because your are using standard output stream through System.out.printlnand exception occurs System.err stream

Try having a variable which will check exceptions and print in same error console if exception occurs :-

boolean isException = false;
try {
        int a=4;
        int b=0;
        int c=a/b;
    }
    catch (Exception ex)
    {
       isException = true
       ex.printStackTrace();
    }
    finally {
       if(isException){
        System.err.println("common");
       }else{
        System.out.println("common");
       }
  }


来源:https://stackoverflow.com/questions/33189792/try-catch-finally-order-of-execution-appears-to-be-random

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!