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)
You must log in to post a comment.