Saturday, July 20, 2013

Java - Exception Stack Trace

Stack traces are helpful when a Java application throws exception. When the Java application is running in a console, we see the trace in console window. In order to log the trace to a file, we have to capture the stack trace in such a way, so as to be able to print it with the structure in tact.  The following Java code snippet, converts a stack trace to String format that can be used to save it to a file.

public static String printStackTrace (Throwable throwable)
{
    final Writer writer = new StringWriter ();
    final PrintWriter printWriter = new PrintWriter (writer);
    throwable.printStackTrace (printWriter);
    return writer.ToString();
}

No comments:

Post a Comment