How to display stack trace on a caught exception?

Your logging framework should have the ability to log exceptions, so simply passing the exception to the proper .error(Object, Throwable) call should be enough:

  • log4j can do it
  • commons logging can do it
  • java.util.logging can do it

If your logging framework can’t do that, or you need the stack trace in a String for any other reason, then it becomes a bit harder. You’ll have to create a PrintWriter wrapping a StringWriter and call .printStackTrace() on the Exception:

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();

Leave a Comment