Organizational Research By

Surprising Reserch Topic

Java – StackTrace to String conversion


There are times when we want to convert the occurred exception to String. In the following program we are converting the stacktrace to String by using Throwable.printStackTrace(PrintWriter pw).

Example: Converting Exception StackTrace to String

package com.beginnersbook.string;
import java.io.PrintWriter;
import java.io.StringWriter;

public class StacktraceToString {
    public static void main(String args[]){
        try{
            int i =5/0;
            System.out.println(i);
        }catch(ArithmeticException e){
            /* This block of code would convert the
             * stacktrace to string by using
             * Throwable.printStackTrace(PrintWriter pw)
             * which sends the stacktrace to the writer
             * that we can convert to string using tostring()
             */
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String stacktraceString = sw.toString();
            System.out.println("String is: "+stacktraceString);
        }
    }
}
Output:

String is: java.lang.ArithmeticException: / by zero
at com.beginnersbook.string.StacktraceToString.main(StacktraceToString.java:8)

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
59 views



Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

...