Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When i launch my personalized exception in java why the parser doesn't follow the order of my code?

Tags:

java

With this code:

class SimpleException extends Exception {}

public class SimpleExceptionDemo {

  public void f() throws SimpleException {
    System.out.println("Throw SimpleException from f()");
    throw new SimpleException();
  }
  public static void main(String[] args) {
    SimpleExceptionDemo sed = new SimpleExceptionDemo();
    try {
      sed.f();
    } catch(SimpleException e) {
      System.err.println("Caught it!");
    }

  }
}

In some case i have this output:

Caught it!
Throw SimpleException from f()

Do you know why "Throw SimpleException from f()" is printed after "caught it"?

like image 621
Brix Avatar asked Dec 01 '22 18:12

Brix


1 Answers

You are printing on two different output streams:

System.out.println("Throw SimpleException from f()");

and

System.err.println("Caught it!");

The order of the messages appearing from the two different streams is not guaranteed... Use the same stream, and it will be OK.

If you're interested in such issues, it might be interesting to read up on

  • Happened-before
  • Java memory model
  • JCIP: Java Concurrency in Practice
like image 56
ppeterka Avatar answered Dec 28 '22 23:12

ppeterka