Difference between e.printStackTrace and System.out.println(e)

前端 未结 6 1508
清歌不尽
清歌不尽 2021-01-31 17:05

Probably a newbie question, but everyone seems to use e.printStackTrace(), but I have always used System.out.println(e) when exception handling. What i

6条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 17:23

    The output stream used is not the same as pointed out by @Brian, but the level of detail is not the same either - you can try with the simple test below. Output:

    With println: you only know what exception has been thrown

    java.lang.UnsupportedOperationException: Not yet implemented

    With printStackTrace: you also know what caused it (line numbers + call stack)

    java.lang.UnsupportedOperationException: Not yet implemented
    at javaapplication27.Test1.test(Test1.java:27)
    at javaapplication27.Test1.main(Test1.java:19)

    public static void main(String[] args){
        try {
            test();
        } catch (UnsupportedOperationException e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
    
    private static void test() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    

提交回复
热议问题