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
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
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");
        }
    }
}

2 Comments

printStackTrace prints to error stream too. So nothing should changes. I suggest to use System.err instead of System.out to get consistent output.
but the it will use the same tread in this case the "main" tread.so the out puts will be in order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.