I was recently asked in an interview on the sequence of execution of an exception case in java, where if the exception is not caught and propagated back to calling code, having finally blocks, then are the finally block statements printed ? If they are then, are they printed before exception or after ?
I tried to run this scenario and found inconsistency in the outputs.
The code I tried is :
public class FinallyExecution {
public static void main(String[] args) {
try{
FinallyExecution.divide(100, 0);
}finally{
System.out.println("finally in main");
}
}
public static void divide(int n, int div){
try{
int ans = n/div;
}
finally{
System.out.println("finally of divide");
}
}
}
And the inconsistent outputs are :
once:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptions.FinallyExecution.divide(FinallyExecution.java:20)
at exceptions.FinallyExecution.main(FinallyExecution.java:9)
finally of divide
finally in main
and next:
finally of divide
finally in main
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptions.FinallyExecution.divide(FinallyExecution.java:20)
at exceptions.FinallyExecution.main(FinallyExecution.java:9)
So what exactly is happening in this case ?? Is the JVM executing the finally blocks and then exiting with exception, or is it in the opposite sequence ? In either case, why is the output inconsistent ?