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.


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


public class TestExample {

	public static void main(String[] args) {
			int y=5/0;
		catch(Exception 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);
		String sStackTrace = sw.toString();
		return sStackTrace;



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