Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a stack trace to a string?

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

like image 838
ripper234 Avatar asked Jul 19 '09 11:07

ripper234


People also ask

How do I read a stack trace file?

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.

How do I print a stack trace to a file?

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.

How do you trace a string in Java?

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.

What is stack trace in thread?

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.


2 Answers

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); 
like image 137
Brian Agnew Avatar answered Oct 14 '22 01:10

Brian Agnew


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)

like image 25
amar Avatar answered Oct 14 '22 01:10

amar