Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Language
Expertise: Beginner
Jul 27, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Exception to String

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.

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, because the 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, the necessary 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);


    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);

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date