I tried to figure out execution order of try-catch-finally
in java
. I thought execution order should be
- try
- catch (if error occurred/ exception caught)
- finally (whether exception caught or not)
But I am confused with the result of the following
public class TryCatchFinally {
static int i = 0;
public static void main(String[] args) {
try {
System.out.println(i++);
main(args);
} catch (StackOverflowError e) {
System.out.println("Catch");
} finally {
System.out.println("Finally");
}
}
}
Out put(part of an out put)
9127
9128
9129
9130
CatcFCatch // what is the wrong here???
Finally
Finally // there are more Finally printed here.
My question is what is really happening here?
Let me add more why it is not printing "Catch"
???
I am getting this out put when run this in IntelliJ IDEA
. But when I run in terminal
I am getting out put as follows.
9151
9152
9153
9154CatchFinallyCatch
Finally
Finally
Finally
Finally