I came across the NoStackTrace
mixin for Exceptions in scala.
Is it good practice to use it, or should it be considered "internal" to scala and left alone?
exceptionsscala
I came across the NoStackTrace
mixin for Exceptions in scala.
Is it good practice to use it, or should it be considered "internal" to scala and left alone?
Best Answer
For a moment, lets head over to Stack Overflow - How slow are Java exceptions?
It turns out that the expensive part of throwing exceptions is the population of the stack trace that goes along with the exception.
This stack trace is very helpful when debugging problems to try to figure out where things are getting called from. One of the standard questions asked of problems is "what is the code" and "what is the stack trace". Without those two things, diagnosing a problem is nigh-impossible.
However, not all exceptions are generated by problems. Some of them, you almost expect.
Consider the situation that you've got a String from some source and you want to get it back into an integer format with Integer.decode.
But that
decode
throws a checkedNumberFormatException
. Ok...But you really don't care about the stack trace there... but its there. And just a tad bit slower because it populated the stack trace.
Thus, in Scala, you've got the
NoStackTrace
:Don't populate what you don't need. You don't care about the stack trace because you are handling it right there and then. This isn't something that is getting passed up, and its not all that exceptional either.
Its not bad practice to use it when you know what you're handling. But, if you're passing this on up the chain - don't use it - you might just need to log where some exception came from.