Java :How to convert a stack trace to a string?


In this blog you will learn way to convert a stack trace to a String which includes all the Stack Trace message of an exception or error.

Why this conversion is required?

This conversion is required if you want to save the message in custom log file for further analysis of log message. The e.getMessage() in Java program only returns small portion of the error, but if you want to see the detailed error then StackTrace will give you complete detail about the error in the program.

Example

To convert stackTrace to a string using printWriter as input for stackTrace to convert in String.

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

public class TestExample {

	public static void main(String[] args) {
		try
		{
			int y=5/0;
		}
		catch(Exception ex)
		{
			System.out.println(convertStackTraceToString(ex));
		}

	}
    /**
     * method to convert stack trace to String
     * @param ex
     * @return
     */
	private static String convertStackTraceToString(Exception ex) {

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		String sStackTrace = sw.toString();
		return sStackTrace;
	}

}

Output


java.lang.ArithmeticException: / by zero
    at com.exceptions.errors.TestExample.main(TestExample.java:11)
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s