Try-catch-finally执行顺序似乎是随机的 [英] Try-catch-finally order of execution appears to be random
问题描述
我正在努力了解 try-catch-finally
执行流程的工作原理。 Stack Overflow用户有两个解决方案可用于执行流程。
其中一个例子是:
尝试{
$代码A将被执行,p $ p>
// ...一些代码:A
}
catch(...){
// ...异常代码:B
}
finally {
// finally code:C
}
如果一切顺利(即A执行时不会抛出异常),则最终将转到
,所以代码C将被执行。如果A执行时抛出异常,那么它将转到B,然后最后到C。
然而,我有不同执行流程,当我尝试它:
try {
int a = 4;
int b = 0;
int c = a / b;
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally {
System.out.println(common);
}
我得到两个不同的输出:
首次输出:
java.lang.ArithmeticException:/ by zero
在substrings.main(substrings.java:15)
lication.AppMain.main(AppMain.java:140)
common
但是,当我第二次运行相同的程序时:
第二个输出: strong>
common
java.lang.ArithmeticException:/ by zero
在substrings.main(substrings .java:15)
我应该从中得出结论?是否会是随机的?
printStackTrace()
标准错误。 System.out.println(common)
输出到标准输出。它们都被路由到同一个控制台,但是它们在该控制台上显示的顺序不一定是执行它们的顺序。
如果您写入在catch块和最后块中都有相同的流(例如,尝试 System.err.println(common)
),你会看到catch块总是在捕获异常时在finally块之前执行。
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?
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.
这篇关于Try-catch-finally执行顺序似乎是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!