File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ #怎么样将堆栈追踪信息转换为字符串类型
2
+ ##问题
3
+ 将` Throwable.getStackTrace() ` 的结果转换为一个字符串来来描述堆栈信息的最简单的方法是什么
4
+
5
+
6
+ ###最佳答案
7
+ 可以用下面的方法将异常堆栈信息转换为字符串类型。该类在Apache commons-lang-2.2.jar中可以找到:
8
+ [ ` org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable) ` ] ( org.apache.commons.lang.exception.ExceptionUtils.getStackTrace\( Throwable\) )
9
+
10
+ ###答案二
11
+ 用 [ ` Throwable.printStackTrace(PrintWriter pw) ` ] ( https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#printStackTrace-java.io.PrintWriter- ) 将对堆栈信息发送到一个输出中:
12
+ ```` java
13
+ StringWriter sw = new StringWriter ();
14
+ PrintWriter pw = new PrintWriter (sw);
15
+ t. printStackTrace(pw);
16
+ sw. toString(); // stack trace as a string
17
+ ````
18
+
19
+ ###答案三
20
+ ```` java
21
+ StringWriter sw = new StringWriter ();
22
+ e. printStackTrace(new PrintWriter (sw));
23
+ String exceptionAsString = sw. toString();
24
+ ````
25
+
26
+ ###答案四
27
+ ```` java
28
+ public String stackTraceToString(Throwable e) {
29
+ StringBuilder sb = new StringBuilder ();
30
+ for (StackTraceElement element : e. getStackTrace()) {
31
+ sb. append(element. toString());
32
+ sb. append(" \n " );
33
+ }
34
+ return sb. toString();
35
+ }
36
+ ````
37
+
38
+ stackoverflow链接:
39
+ http://stackoverflow.com/questions/1149703/how-can-i-convert-a-stack-trace-to-a-string
You can’t perform that action at this time.
0 commit comments