Skip to content

Commit 223cc53

Browse files
XealRedanmaibin
authored andcommitted
BAEL-874 - How to convert stacktrace to String in Java? (eugenp#1771)
1 parent a623ddb commit 223cc53

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.exceptions;
2+
3+
import org.apache.commons.lang3.exception.ExceptionUtils;
4+
5+
import java.io.PrintWriter;
6+
import java.io.StringWriter;
7+
8+
public class StackTraceToString {
9+
10+
public static void main(String[] args) {
11+
// Convert a StackTrace to String using core java
12+
try {
13+
throw new NullPointerException();
14+
} catch (Exception e) {
15+
StringWriter sw = new StringWriter();
16+
PrintWriter pw = new PrintWriter(sw);
17+
e.printStackTrace(pw);
18+
19+
System.out.println(sw.toString());
20+
}
21+
22+
// Convert a StackTrace to String using Apache Commons
23+
try {
24+
throw new IndexOutOfBoundsException();
25+
} catch (Exception e) {
26+
System.out.println(ExceptionUtils.getStackTrace(e));
27+
}
28+
}
29+
30+
}

0 commit comments

Comments
 (0)