What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
To read this stack trace, start at the top with the Exception's type - ArithmeticException and message The denominator must not be zero . This gives an idea of what went wrong, but to discover what code caused the Exception, skip down the stack trace looking for something in the package com.
For example: try { File f = new File(""); } catch(FileNotFoundException f) { f. printStackTrace(); // instead of printing into console it should write into a text file writePrintStackTrace(f. getMessage()); // this is my own method where I store f.
Using StringWriter and PrintWriter in the catch block, and the purpose behind it is to print the given output in the form of a string. Now print the stack trace using the printStackTrace() method of the exception and after that write it in the writer. And finally, convert it into a string using the toString() method.
A stack trace is a user-friendly snapshot of the threads and monitors in a Virtual Machine for the Java platform (Java Virtual Machine or JVM machine). A thread dump shows what every thread in a JVM is doing at a given time and is useful in debugging.
Use Throwable.printStackTrace(PrintWriter pw)
to send the stack trace to an appropriate writer.
import java.io.StringWriter; import java.io.PrintWriter; // ... StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace);
One can use the following method to convert an Exception
stack trace to String
. This class is available in Apache commons-lang which is most common dependent library with many popular open sources
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With