Posts Tagged With ‘Exception&8217


How to get Exception Stacktrace to String

If you ever wanted to execute something like:

System.out.println(exception.PrintStacktrace());

Then you have come to the right place.

getStringStackTrace()

will return a string which would contain stacktrace. Later, you can log that in a DB or in a file or just print on console.

    public String getStringStackTrace(Throwable t)
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            t.printStackTrace(pw);
            pw.flush();
            sw.flush();
            return sw.toString();
        }

Here is one usage example:

import java.io.PrintWriter;
import java.io.StringWriter;


public class Test {

	public static void main(String args[])
		{

			try
				{
					throw new RuntimeException("Test getStringStrackTrace");
				} catch (Exception e)
				{
					e.printStackTrace();
					System.out.println(getStringStackTrace(e));
				}

		}
}

Output:

java.lang.RuntimeException: Test getStringStrackTrace
	at com.trgr.cobalt.performance.integrationtests.Test.main(Test.java:13)