1

I am aware that many questions about try-catch-finally blocks have been asked in this site. But I have a different doubt. I get different outputs when the code below is run multiple times.

I have a very simple class as follows:

Practice.java

public class Practice {
    public static void main(String []args) {
         System.out.println(getInteger());
    }

    public static int getInteger() {
       try {
           System.out.println("Try");
           throwException();
           return 1;
       } catch(Exception e) {
           System.out.println("Catch Exception");
           e.printStackTrace();
           return 2;
       } finally {
            System.out.println("Finally");
      }
    }

   private static void throwException() throws Exception {
       throw new Exception("my exception");
   }
}

The output when I first run the code above is as follows:

Try
Catch Exception
Finally
2
java.lang.Exception: my exception
    at exceptionHandling.Practice.throwException(Practice.java:22)
    at exceptionHandling.Practice.getInteger(Practice.java:10)
    at exceptionHandling.Practice.main(Practice.java:4)

A different output when I run the code again is given below:

Try
Catch Exception
java.lang.Exception: my exception
    at exceptionHandling.Practice.throwException(Practice.java:22)
    at exceptionHandling.Practice.getInteger(Practice.java:10)
    at exceptionHandling.Practice.main(Practice.java:4)
Finally
2

Can somebody please explain such output?

1 Answer 1

5

You use different filehandles. Your output goes to System.out, e.printStackTrace(); writes to System.err which will flush on different times.

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

1 Comment

Thanks. I did not know this. I wanted to find the sequence of execution

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.