Print the stack trace of an exception

后端 未结 9 1240
有刺的猬
有刺的猬 2020-12-05 03:31

How do I print the stack trace of an exception to a stream other than stderr? One way I found is to use getStackTrace() and print the entire list to the stream.

9条回答
  •  爱一瞬间的悲伤
    2020-12-05 04:12

    I have created a method that helps with getting the stackTrace:

    private static String getStackTrace(Exception ex) {
        StringBuffer sb = new StringBuffer(500);
        StackTraceElement[] st = ex.getStackTrace();
        sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
        for (int i = 0; i < st.length; i++) {
          sb.append("\t at " + st[i].toString() + "\n");
        }
        return sb.toString();
    }
    

提交回复
热议问题