HOWTO: Get a Java Stack Trace as a String (getStackTraceAsString)

| No TrackBacks
Here's a quick tip that might be useful to some Java nuts out there.  Often in Java, it can be helpful to save a stack trace as a String.  This is useful when an application (a web-app or standalone client application) needs to "report back" to a central server that an error occurred.  When the client app pings the server to alert it of an Exception case, it's very helpful to also include the stack trace in the ping.  If you ever find yourself needing to do this, here's how:

/**
* Given a Throwable, gets the full stack trace for the
* Exception or Error as a String. Returns an empty string
* if something went wrong (so the caller won't fail with a
* null pointer exception later).
* @param t
* @return
* @author kolichko Mark Kolich
*/
public static String getStackTraceAsString ( Throwable t ) {

final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
String trace = new String();

try {
t.printStackTrace( pw );
pw.flush();
sw.flush();
trace = sw.toString();
}
catch ( Exception e ) { }
finally {
try {
sw.close();
pw.close();
}
catch ( Exception e ) { }
}

return trace;

}

Enjoy.

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on May 20, 2009 5:59 PM.

Symantec AntiVirus: HOWTO Disable/Unlock Scheduled Administrator Scans was the previous entry in this blog.

HOWTO: Whole Disk Backup and Recovery with dd, gzip, and p7zip (Linux on a CD too) is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.