0

Hi I have written below code. After each execution it is displaying output in a different order.

 public class ExcetionInFinallyBlockDemo1 {
    public static void main(String[] args) {
        int a[] = new int[5];
        try {
            System.out.println("Accessing sixth element" + a[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally block start");
            try {
                double divide = a[3] / 0;
                System.out.println("Divide result:" + divide);
            } catch (ArithmeticException e2) {
                e2.printStackTrace();
            }
            System.out.println("Finall block end");
        }
        System.out.println("rest of the code");
    }

}

first run output:

java.lang.ArrayIndexOutOfBoundsException: 5
        at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
    java.lang.ArithmeticException: / by zero
finally block start
    at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)
Finall block end
rest of the code

second run output:

java.lang.ArrayIndexOutOfBoundsException: 5
        at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
finally block start
Finall block end
rest of the code
java.lang.ArithmeticException: / by zero
    at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)

Third run output:

java.lang.ArrayIndexOutOfBoundsException: 5
    at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:11)
java.lang.ArithmeticException: / by zero
    at com.sanju.exceptionHandling.ExcetionInFinallyBlockDemo1.main(ExcetionInFinallyBlockDemo1.java:17)
finally block start
Finall block end
rest of the code

Could you please explain why it is printing in different order each time ?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Pranav
  • 25
  • 9

1 Answers1

3

This is because the two output streams System.out and System.err are buffered independently.

Although i don't yet fully understand why - my first answer - flushing the buffers - actually don't help (as bowmore suggests) and it seems to be impossible to do this without using your own synchronized solution.

An easy workaround is using only one buffer for err and out like this:

System.setErr(System.out);

as already mentioned here: Race between System.out and System.err in java

ospf
  • 169
  • 9
  • Flushing won't magically synchronize the two buffers. – bowmore Jul 03 '17 at 13:45
  • Youre right - but i was expecting the output reaching the output-buffer (the console) the moment flush returns. Obviously it doesn't. – ospf Jul 04 '17 at 10:09
  • Alternatively, in his snippet he can simply print stacktraces to System.out : `e.printStacktrace(System.out)` – bowmore Jul 04 '17 at 10:16