Skip to content
Rezha Julio
Go back

Converting Stacktrace to String

1 min read

To store a stack trace as a string, you can use Throwable.printStackTrace(...) For example:

public static String getStackTrace(
Throwable throwable
){
Writer result = new StringWriter();
PrintWriter printWriter =
new PrintWriter(result);
throwable.printStackTrace(printWriter);
return result.toString();
}

In the above example, getStackTrace takes a Throwable as a parameter and uses printStackTrace to print it to a PrintWriter output stream. This output is collected by the StringWriter and converted to a string using StringWriter.toString().


Related Posts


Previous Post
Updating interfaces by using default methods
Next Post
Synchronized Statement in Java