Consider the following test case:
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++;
}
}
}
With output:
0: inner catch
1: finally
---
2: finally
3: outer catch
What’s the explanation for why in test() catch happens before finally while in test2() it’s the other way around?
Because the
tryblock intest2()doesn’t have acatchblock, only afinally. The code won’t “jump back” to the caller to fall intocatchand then “jump ahead” to thefinallyto continue there as you seem to think.