import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceToString {
public static void main(String[] args) {
try {
throw new Exception("Test exception");
} catch (Exception e) {
String stackTraceString = getStackTraceString(e);
System.out.println(stackTraceString);
}
}
public static String getStackTraceString(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
return sw.toString();
}
}
java.lang.Exception: Test exception
at StackTraceToString.main(StackTraceToString.java:7)
try-catch
block. We then call the getStackTraceString()
method, passing the caught exception as input. This method converts the stack trace of the exception to a string using a StringWriter
and a PrintWriter
, and returns the resulting string.getStackTraceString()
method takes a Throwable
object as input, which can be any object that represents an exception or error. It creates a new StringWriter
and a new PrintWriter
, passing the StringWriter
as the output destination for the PrintWriter
. It then calls the printStackTrace()
method of the Throwable
object, passing the PrintWriter
as the output destination. This causes the stack trace of the Throwable
object to be written to the StringWriter
. Finally, it returns the string that was written to the StringWriter
.