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.
package com.bytenota;


public class StackTraceToStringExample {
    public static void main(String[] args) {
        try {
        } catch (Exception ex) {
            // convert StackTrace to String
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            String exceptionAsString = sw.toString();
    public static int getStringLength(String str) throws Exception {
        return str.length();