The best overview of the error handling options in the standard library we are aware of is tersesystems.com/2012/12/27/error-handling-in-scala, by Will Sargent, a former Lightbender.
Digression: One topic he doesn’t cover is why checked exceptions have fallen out of favour. In short, given our current approaches to writing generic code, we’re unable to abstract over the types of checked exceptions. What would be the throws clause of Function1.apply
, or a higher order function like Option.map
? This tension is covered in some (academic) detail in http://www.cs.kuleuven.be/publicaties/rapporten/cw/CW407.pdf. Lukas Rytz (now in the Lightbend Scala team) researched “lightweight effect polymorphism” for his thesis. This made it as far as a prototyped extension for the compiler (https://github.com/lrytz/efftp/wiki/Exceptions), but is not likely to be developed further and to land in mainstream Scala.
You can actually declare exceptions in Scala with the @throws
annotation, but there is no compiler enforcement of Java’s “catch or redeclare” rule. (It will force Java clients to deal with them, though.)
If you decide to introduce a data type to explicitly represent potential failures, you have to find the best fit with your use case.
Those third party data types differ from the the standard Either
in two ways: 1) being biased, meaning you can call map
or flatMap
and operate on the Success value; 2) some allow error accumulation, which can elegantly express code that has to report multiple errors in one pass, rather than failing fast on the first error. Form validation is a typical use case here.
Please note that we do not maintain the code of scalactic or scalaz and these are not covered by your support subscription. Use at your own risk.