class exception1 {
public static void main(String s[]) {
String v[] = new String[2];
try {
main(v);
System.out.println(5 / 0);
}
catch (Exception e) // or (ArithmeticException e)
{
System.out.println(e); // Java.lang.ArithmeticException: / by zero
}
finally {
System.out.println("AAAA");
}
System.out.println("after finally normal execution");
}
}
When i run this code, i get countless AAAA’s till the stackoverflow error occurs. My question is main(v); calls the main again and yet finally runs 🙁 ? Control flow is somewhat out of my conscience. Is finally so arrogant that it does not even care about main?
First of all, note that
StackOverflowErroris anErrorand not anException, so it won’t be caught in yourcatch (Exception e).When the
StackOverflowErroris thrown, that exception will propagate up in the call stack. Each time a stack-frame returns exceptionally, it’s finally clause will be executed.(The
0/5expression is not reachable, as you’ve probably discovered.)Here’s a picture of what happens: