How To Convert a StackTrace To a String in Java
This example shows you the way to convert a StackTrace to a String in Java.
The below code we simply define getStringLength
method, which returns the length of the given string. An exception will be thrown if we set a null
value to it. And then in the catch block, we convert the Exception
to String using StringWriter
and PrintWriter
objects.
StackTraceToStringExample.java
package com.bytenota;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToStringExample {
public static void main(String[] args) {
try {
getStringLength(null);
} catch (Exception ex) {
// convert StackTrace to String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exceptionAsString = sw.toString();
System.out.println(exceptionAsString);
}
}
public static int getStringLength(String str) throws Exception {
return str.length();
}
}