通常输出异常信息的形式为:
e.printStackTrace();
通过查看Throwable类,会发现存在几个重载的方法:
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintStream s) {
printStackTrace(new WrappedPrintStream(s));
}
public void printStackTrace(PrintWriter s) {
printStackTrace(new WrappedPrintWriter(s));
}
所以,我们可以通过IO流将异常信息转换成字符串输出:
public class ExceptionStackTrace {
public static void main(String[] args) throws Exception {
try {
String str = null;
str.equals("AA");
} catch (Exception e) {
e.printStackTrace();
System.out.println(getStackTrace(e));
System.out.println(getExceptionStackTrace(e));
}
}
public static String getStackTrace(Throwable throwable) throws IOException {
if (null == throwable) {
return null;
}
Writer result = null;
PrintWriter printWriter = null;
try {
result = new StringWriter();
printWriter = new PrintWriter(result);
throwable.printStackTrace(printWriter);
return result.toString();
}
finally {
printWriter.close();
result.close();
}
}
public static String getExceptionStackTrace(Throwable throwable) throws IOException {
if (throwable == null) {
return null;
}
ByteArrayOutputStream baos = null;
PrintStream printStream = null;
try {
baos = new ByteArrayOutputStream();
printStream = new PrintStream(baos);
throwable.printStackTrace(printStream);
return baos.toString();
}
finally {
printStream.close();
baos.close();
}
}
}
运行之后,输出的结果:
java.lang.NullPointerException
at com.example.reflection.Reflection.main(Reflection.java:14)
java.lang.NullPointerException
at com.example.reflection.Reflection.main(Reflection.java:14)
java.lang.NullPointerException
at com.example.reflection.Reflection.main(Reflection.java:14)