0

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 ?

Prajakta
  • 89
  • 1
  • 9

1 Answers1

1

You are printing to System.out whereas the uncaught exception stacktrace is printed to System.err. You see both content in the console, but it is undefined in which order.

If you change your debug prints to use System.err then the order is consistent.

wero
  • 32,544
  • 3
  • 59
  • 84