1

Consider the following class with methods: a() calling b() which in turn calls c().

public class ReThrower {

    public static void a(int a1){
        try{
           a1+=1;
           b(a1);
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at a");
            throw e;
        }
    }

    public static void b(int b1){
        try{
            b1+=1;
            c(b1);
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at b");
            throw e;
        }

    }

    public static void c(int c1){
        int zero=0,result;
        try{
            result=c1/zero;
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at c");
            e.printStackTrace();
            throw e;
        }

    }

    public static void main(String[] args) {
        a(5);
    }

}

When i ran the above code, the initial output received was:

Exception caught at c
java.lang.ArithmeticException: / by zero
Exception caught at b
Exception caught at a
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)

Even before the c() printed the complete stacktrace, the sysout included in b() and a() has already been executed. However,When i ran it again, the output changed as such:

    Exception caught at c
Exception caught at b
Exception caught at a
java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)

Given that this is single threaded, why is there a change in behaviour in multiple runs?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
seriousgeek
  • 992
  • 3
  • 13
  • 29

1 Answers1

3

e.printStacktrace prints to System.err whereas you print the rest of the lines with System.out. And when you print to both streams the result can look out of order.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783