Sunday, April 17, 2005

Java: Convert StackTrace to String

Okay. This is how you could get a StackTrace and write it to a String:

//code here
catch(Exception e)
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();


Anonymous said...

Fine, exactly wehat i was looking for.
By the way, only google hit to the following search terms:

java exception "stacktrace to string"


enginerd said...

Yep! In fact, this post remains one of the most frequently visited!!!

Glad that you found it useful :)

Anonymous said...

Thank you so much. This was a great help to me.

Raja Nagendra Kumar said...

Is there any way to have the same in J2ME..

Most the VM's on Phone don't even pass the message version of the exception.. and hence at least knowing the stack trace would help a lot..

Raja Nagendra Kumar,

Juanjo Vega said...

Thanks a lot. I was looking for something so simple, not as other complex solutions with classes to convert stack traces.

fridi said...

Excellent and pritty simple ;-)

Anonymous said...

Great thanks!! :-)

Tom Jenkinson said...


Anonymous said...

Thanks a lot! Should be part of the API.