The dreaded printStackTrace()

Ah, the ubiquitous ex.printStackTrace().

Does this look familiar?

try {

// something

} catch (Exception ex) {

ex.printStackTrace();

}

I will assume the the (ab)users of this construct are familiar with the various logging systems available, the mostĀ prevalentĀ of which are:

… and understand why squirting output to stdout isn’t a clever idea, but don’t know how to extract the required exception information into a sensible string format.

So, here’s a Java snippet to insert as appropriate:

StringWriter w = new StringWriter();
ex.printStackTrace(new PrintWriter(w));
Now we can get at the exception text using:
w.toString()

Nice and simple, and a lot cleaner than dumping the output.

This entry was posted in java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>