Scala – Is It Good Practice to Use NoStackTrace

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.

Integer foo = Integer.decode(str);

But that decode throws a checked NumberFormatException. Ok...

Integer foo;
try {
    foo = Integer.decode(str);
} catch (NumberFromatException e) {
    // raise an error back to the input form
}

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:

A trait for exceptions which, for efficiency reasons, do not fill in the stack trace. Stack trace suppression can be disabled on a global basis via a system property wrapper in scala.sys.SystemProperties.

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.

Related Topic