I'm getting irregular output for this program? Why?

Finally example

public class FinallyExample {

    public static void main(String[] args) {
        new FinallyExample().dothework();
    }
    public void dothework()
        {
            Object o=null;
            for(int i=0;i<=4;i++)
            {
                System.out.println(" "+i);
        try{ o=makeObj(i);}catch(IllegalArgumentException e){System.err.println("Error: ("+e.getMessage()+").");}
            finally{System.err.println("All done");
            /*if(o==null)
            {
                System.exit(0);
            }*/
            }
            System.out.println(o);
        }
        }
    public Object makeObj(int type) throws IllegalArgumentException
    {
        if(type==1) throw new IllegalArgumentException ("Don't like type"+type);
        return null;
        }
}

The sequence of output is always different!

I'm using eclipse.

O/P- All done Error: (Don't like type1). 0 //this line should be print when i=1 null 1

All done null 2 All done null 3 All done null 4 All done null

O/P- 0 All donenull 1

Error: (Don't like type1). All done null 2 All done null 3 All done null 4 All done null

Jon Skeet
people
quotationmark

Basically, you're writing to System.out and System.err. It's unclear (and implementation-specific) exactly how much data those will buffer, or when they will be flushed, but you shouldn't necessarily expect that to be consistent every time.

I expected that calling System.out.flush() after writing to System.out, and System.err.flush() after writing to System.err would fix this - but in Eclipse at least, it doesn't seem to. (Running the same code in a Windows command prompt gives the same output every time even without the flush.)

Basically, this appears to be an artefact of the Eclipse console implementation. I wouldn't worry about it - just be aware of it when you're trying to diagnose things. (If you send all diagnostic output to the same stream, it won't be a problem.)

people

See more on this question at Stackoverflow