7
class TestExceptions {

    public static void main(String[] args) throws Exception {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            throw new RuntimeException();
        } finally {
            System.out.println("finally");
        }
    }
}

Following are the outputs when I try to run the code in eclipse multiple times. I believed so far that whenever the last line of the code from either try/catch block is about to be executed (which could be return or throws new Exception() type of stmt), finally block will be executed, but here the output different every time? Can anyone clarify if my assumption is right or wrong?

try
catch
Exception in thread "main" finally
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)


Exception in thread "main" try
catch
java.lang.RuntimeException
    at TestExceptions.main(TestExceptions.java:9)
finally
Sebastian S
  • 4,420
  • 4
  • 34
  • 63
coretechie
  • 1,050
  • 16
  • 38
  • 1
    Related: http://stackoverflow.com/questions/23588123/why-does-the-execution-order-between-the-printstacktrace-and-the-other-methods – JonK Aug 11 '15 at 08:09

2 Answers2

9

This is clearly because eclipse is printing the error stream and output stream without proper synchronization in console. Lot of people have seen issues because of this.

Execute the program in a command prompt and you will see proper output every time.

Codebender
  • 14,221
  • 7
  • 48
  • 85
  • Yes, I got below output when I ran it multiple times from command prompt . try catch finally Exception in thread "main" java.lang.RuntimeException at TestExceptions.main(TestExceptions.java:9) Eclipse , error stream and output stream are async, that's something new I learnt today. But they are still accessing the same console and even command prompt is accessing single output console..why such a huge difference? – coretechie Aug 11 '15 at 09:09
0

while agreeing with @Codebender, you can replace all the thows exception and replace them with printStackTrace(); then the exceptions and out will be printed in syn. EG:

 public static void main(String[] args) throws Exception {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }
    }
}
Kamidu Punchihewa
  • 1,241
  • 10
  • 18
  • `printStackTrace` prints to error stream too. So nothing should changes. I suggest to use `System.err` instead of `System.out` to get consistent output. – talex Aug 11 '15 at 08:46
  • but the it will use the same tread in this case the "main" tread.so the out puts will be in order. – Kamidu Punchihewa Aug 12 '15 at 03:13