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)