什么是第一 - 最后还是阻止? [英] What comes first - finally or catch block?
本文介绍了什么是第一 - 最后还是阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下测试用例:
public class Main {
static int a = 0;
public static void main(String[] args) {
try {
test();
System.out.println("---");
test2();
}
catch(Exception e) {
System.out.println(a + ": outer catch");
a++;
}
}
public static void test()
{
try {
throw new Exception();
}
catch (Exception e) {
System.out.println(a + ": inner catch");
a++;
}
finally {
System.out.println(a + ": finally");
a++;
}
}
public static void test2() throws Exception
{
try {
throw new Exception();
}
finally {
System.out.println(a + ": finally");
a++;
}
}
}
输出:
0: inner catch
1: finally
---
2: finally
3: outer catch
为什么在 test()中有什么解释
捕获发生在最后,而在 test2()
它是相反的方式?
What's the explanation for why in test()
catch happens before finally while in test2()
it's the other way around?
推荐答案
因为 test2()
中的尝试
块没有 catch
阻止,只有最后
。代码不会跳回调用者进入 catch
然后跳转到最后
按照你的想法继续那里。
Because the try
block in test2()
doesn't have a catch
block, only a finally
. The code won't "jump back" to the caller to fall into catch
and then "jump ahead" to the finally
to continue there as you seem to think.
这篇关于什么是第一 - 最后还是阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文