0

When I ran this program multiple times, I got different output:

public class Demo {
public static void main(String[] args) {
    try {
        System.out.println("try block");
        int a = 10 / 0;
    } catch (Exception e) {
        System.out.println("catch block");
        int a = 10 / 0;
    } finally {
        System.out.println("finally block");
        int a = 10 / 0;
    } 
}

}

First output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
  at kd.demo.Demo2.main(Demo2.java:14)
try block
catch block
finally block

Second output:

Exception in thread "main" try block
catch block
finally block
java.lang.ArithmeticException: / by zero
  at kd.demo.Demo2.main(Demo2.java:14)

Third output:

Exception in thread "main" try block
catch block
finally block
java.lang.ArithmeticException: / by zero
  at kd.demo.Demo2.main(Demo2.java:14)

When I compiled and executed this program multiple times, I got different output. Most of the time I got the third one which is not a problem. However, I am confused about other output (first and second).

seaotternerd
  • 5,872
  • 2
  • 40
  • 58
deen
  • 1,883
  • 6
  • 25
  • 47

1 Answers1

4

You are writing to both System.out (your println statements) and System.err (the stack trace that will be printed from the uncaught exception raised in the finally block).

The order in which that interleaving will be displayed on your screen is rather indeterministic.

You could "fix" this by sending your messages to System.err instead of System.out. Then everything will go to the same stream.

Thilo
  • 241,635
  • 91
  • 474
  • 626