javaprintstacktrace

Why is printstacktrace() of exception method does not print to console when ever called?


Whenever we are trying to print stack trace using printStackTrace() method, why the output is not in expected order? suppose we have some print statements along with printStackTrace() and the output is not in expected order.

public class Main {

    public static void main(String[] args) {
        Main m = new Main();
        m.test1();
        System.out.println("main method");
    }

    public void test1() {
        System.out.println(test2());
        System.out.println("test1");
    }

    public int test2() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.out.println("exception");
            e.printStackTrace();
        } finally {

    }
    return 2;
}

}

Expected output should be :

exception

java.lang.Exception

at com.infor.jdbc.Main.test2(Main.java:18)

at com.infor.jdbc.Main.test1(Main.java:12)

at com.infor.jdbc.Main.main(Main.java:7)

2

test1

main method

But actual result is:

exception

java.lang.Exception          //from printStackTrace

2

test1

main method

at com.infor.jdbc.Main.test2(Main.java:18)  //from printStackTrace

at com.infor.jdbc.Main.test1(Main.java:12)

at com.infor.jdbc.Main.main(Main.java:7)

Solution

  • Buffered outputstreams are being written to two separate output(s) without flushing ("stderr" and "stdout"). Print your message, print the stack trace and then flush and you will see the behavior you expected.

    public int test2() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.err.println("exception");
            e.printStackTrace(System.err);
            System.err.flush();
        } finally {
    
        }
        return 2;
    }