

In that code I intentionally wrap an IOException inside a custom exception, which I then throw from my method. * otherwise it throws an exception wrapped in a `Failure`.Ĭlass AlsException(s: String, e: Exception) extends Exception(s: String, e: Exception) * This method returns a `Success` if everything goes well, println(t.getStackTrace.mkString("\n")) Import scala.util.Ĭase Success(i) => println(s"success, i = $i") The output from this new approach is much more readable, as I verified with this little test program:

I just use this approach when creating a string to work with a logger. This new approach works really well at keeping the stack trace formatting, as I’ll show in the next example.Īs I note at the end of this article, you don’t need to use this technique when writing to STDERR. In fact, here’s the Java version of the code, which I just used to log exceptions in Android: I wrote that code in Scala, but as you can see, it converts to Java very easily. The best way to format and log stack tracesīut recently I learned the following technique, which does a much better job of keeping the formatting when getting the text from a stack trace, and then writing it to a file with a logger:Įxception.printStackTrace(new PrintWriter(sw))

In that code, getStackTrace returns a sequence, which I convert to a String before printing it. this works, but it's not too useful/readable In Scala I used to get the text from a stack trace and then log it like this: I’ll use Scala code here, but it converts easily to Java. This tutorial shows the best way I know to log exceptions.
#STACK TRACE FORMATTER HOW TO#
par, and performanceĪs a quick note, I just got a little bit better about how to log stack traces when writing Java or Scala code. show more info on classes/objects in repl.
