How do I get an exception stack trace message?

In this example we use the and class to convert stack trace exception message to a string.



public class StackTraceToString {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (Exception e) {
            // Create a StringWriter and a PrintWriter both of these object
            // will be used to convert the data in the stack trace to a string.
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);

            // Instead of writing the stack trace in the console we write it
            // to the PrintWriter, to get the stack trace message we then call
            // the toString() method of StringWriter.

            System.out.println("Error = " + stringWriter);

This code snippet print the following output:

Error = java.lang.ArithmeticException: / by zero

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.