Question

I have a simple Arithmetic Program typed in Eclipse. When run the program in Eclipse the output appears in weird order each time I run. Sometimes The exception comes at last print statement comes first (which is the right way). Some times it comes vise-versa in a jumbled up order. Why it is happening & how to rectify it? Is there any setting to make it print in a right way each time I execute. The below screen shots show how it appears. Please help me rectify this problem.

Correct Order: Correct Order when run

Incorrect Order when we run couple times after Incorrect Order

 package com;

    public class Abc {

        /**
         * @param args
         */
        public static void main(String[] args) {

            System.out.println("begin main");
            // TODO Auto-generated method stub
            int a = 10;
            int b = 0;
            int c = 0;


            System.out.println("value of a BD is " + a);
            System.out.println("value of b BD is " + b);
            System.out.println("value of c BD is " + c);

            c = a/b; //Arthmetic Exception

            System.out.println("value of a AD is " + a);
            System.out.println("value of b AD is " + b);
            System.out.println("value of c AD is " + c);



        }

    }
Was it helpful?

Solution 2

A bit more detail: the output from your print statements is going to System.out. However, the exception messages are going to System.err (see this). These two are separate output streams that both happen to go to the same place: your console. They are buffered and processed independently. In the second situation you show, the print statements are buffering up but not yet printed when the exception happens.

edit There is an added complication here, which is that the Eclipse console is not a real Windows console. As noted here among other places, there have in the past been problems with the Eclipse console on Windows platforms because Windows does not give Eclipse a good way to make its console behave just like a native console. If you add flush calls and still have problems, try running your program from a command prompt and see if that makes a difference.

OTHER TIPS

Two different streams are being used here. You are using System.out. and the exception is printed with System.err. They are buffered, so one's output may print before the other's.

You can call System.out.flush(); before the exception line:

System.out.flush();
c = a/b;  //Arthmetic Exception
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top