BAEL-874 - How to convert stacktrace to String in Java? (#1771)

This commit is contained in:
Alexandre Lombard 2017-05-04 12:20:03 +02:00 committed by maibin
parent a623ddbf45
commit 223cc5357f
1 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.exceptions;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
// Convert a StackTrace to String using core java
try {
throw new NullPointerException();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
}
// Convert a StackTrace to String using Apache Commons
try {
throw new IndexOutOfBoundsException();
} catch (Exception e) {
System.out.println(ExceptionUtils.getStackTrace(e));
}
}
}