Getting the stack trace from an exception in Java

Tags:

If you need to get the StaceTrace from an exception it isn't quite as simple as you may think. It requires a couple of additional lines of code and an important replacement of certain String values in order to make it usable. The following are the import statements you need:

import java.io.StringWriter;
import java.io.PrintWriter;
import java.util.regex.Matcher;

and this is the method:

/**
 * Returns the exceptions stack trace as a string. The string is sanatised by Matcher.quoteReplacement(stackTrace)
 * and so it is safe to use in regular expressions etc. as characters like '$' are escaped.
 *
 * @param exception The exception whos stack trace you want as a string
 * @return A string that is the additive frames of the stack trace.
 */
public String exceptionStackTraceToString(Exception exception){

    StringWriter stringWriter = new StringWriter();
    exception.printStackTrace(new PrintWriter(stringWriter));
    String stackTrace = stringWriter.toString();

    // As stackTrace may contain regular expression special characters we need to make them harmless first
    return Matcher.quoteReplacement(stackTrace);
}

I have used this as a helper class in sending an email to an administrator and also in writing the exception StackTrace to the database.

Comments:

Post a Comment:

HTML Syntax: Allowed