对于异常Throwable内容需要过滤或解析转换后再输出,相应大家用的最多的应该是e.printStackTrace将异常内容直接打印出来,其实还有void java.lang.Throwable.printStackTrace(PrintWriter s)可以将堆异常输出到PrintWriter,用法如下
package com.xwood.demo.main;@b@@b@import java.io.PrintWriter;@b@import java.io.StringWriter;@b@import java.io.Writer;@b@@b@public class Exception2String {@b@@b@ public static void main(String[] args) {@b@ @b@ Throwable e=new Exception("1324");@b@ e.printStackTrace();@b@ @b@ Writer result = new StringWriter();@b@ PrintWriter printWriter = new PrintWriter(result);@b@ e.printStackTrace(printWriter);@b@ System.out.println(result.toString());@b@@b@ }@b@@b@}
控制台输出如下