devxlogo

Exception to String

Exception to String

Question:
Given an exception, how do I convert the stack trace into a string? I want to capture the entire contents, the message and the trace, to a string.

Answer:
The answer to this question at first glance seems trivial, but is actually something that can stump someone who’s advanced beyond the rank of beginner. Java programmers usually print stack traces printStackTrace() and fetch exception messages as strings with getMessage(). Hardly ever does anyone want to capture a stack trace as a string. That appears to be why JavaSoft did not provide a getStackTrace() convenience method.

The java.lang.Throwable class provides three printStackTrace methods. The most commonly used is the one that takes no arguments, which prints a stack trace to standard output by default. There is no need to separately print the message accompanying an exception when you print a stack trace, becausethe stack trace includes the message. The two other printStackTrace methods take PrintStream and PrintWriter arguments. This means that if you want to store a stack trace in a string, you have to write to it through either a PrintStream or a PrintWriter.

The simplest way to do this is to wrap a StringWriter with a PrintWriter. The accompanying code listing shows how to do this. Since this is an operation you might want to perform often, thenecessary code has been encapsulated in a static method called getStackTrace, which does the necessary dirty work.

import java.io.*;public final class StringStackTrace {  public static final String getStackTrace(Throwable e) {    PrintWriter printer;    StringWriter string;    string  = new StringWriter();    printer = new PrintWriter(string);    e.printStackTrace(printer);    printer.close();    return string.toString();  }  public static final void main(String args[]) {    String trace = null;    try {      throw new Exception("This is a test.");    } catch(Exception e) {      trace = StringStackTrace.getStackTrace(e);    }    System.out.println(trace);  }}
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist