My Wiki

July 25, 2006

Convert exception stacktrace to String object

Filed under: Java — jaikiran @ 12:31 pm

Usually whenever a exception occurs, we use the method printStackTrace() on the exception object to display the stacktrace. However, if the stacktrace has to be stored into a String  object then the following piece of code will prove handy:

  /**
     * Creates and returns a {@link java.lang.String} from <code>t</code>’s stacktrace 
     * @param t Throwable whose stack trace is required
     * @return String representing the stack trace of the exception
     */
    public String getStackTrace(Throwable t) {
        StringWriter stringWritter = new StringWriter();
        PrintWriter printWritter = new PrintWriter(stringWritter, true);
        t.printStackTrace(printWritter);
        printWritter.flush();
        stringWritter.flush();
 

       return stringWritter.toString();
    }

Advertisements

5 Comments »

  1. Hi, I’m Brazilian.
    His method was very important for me ’cause this returns the exception complete.

    Thank’s!

    Comment by Paulo Nepomuceno — October 27, 2006 @ 1:32 pm

  2. Glad to know, it helped you.

    -Jaikiran

    Comment by jaikiran — October 28, 2006 @ 6:18 am

  3. You Rock…Very useful method

    Comment by Sd — December 20, 2006 @ 9:29 am

  4. Thanks 🙂

    Comment by jaikiran — December 23, 2006 @ 4:42 am

  5. Thanks man .Very useful stull

    Comment by Sarang — September 25, 2008 @ 5:55 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: