In my scala code (libraries as well as applications) I currently use a mixture of Option
and Try
, whenever either of both feels more apropriate.
I tend to implement "doSomething"-methods which can succeed with a return value or with a failure with Try
. That is, they can contain code which throw, or, when I detect errors "by hand", I artificially create a Throwable
and return a Failure
. The return value of those methods hence is a Try[ReturnType]
.
Now I read that creating exceptions is somewhat suboptimal, because it creates a stack trace (and hence is slow), which I don't even need. I also saw examples using a subclass of ControlThrowable
, which don't create a stack trace, however they also don't have a message, and Try
of course won't catch it.
Now my concrete question would be, should I generally favour Either
over Try
when I want to do runtime error-handling / method return values, and use Try
only in situations where I actually need to catch something (e.g. thirdparty code)?
That way I would not have to create clumsy Throwable
s, but instead only use e.g. strings in Left
for errors.
So basically:
Option
: every day usage for something which plain has a value or notTry
: catching exceptions within methods, but not used as return valueEither
: universal return value, containing error (string) or success value
Would this concept work out well, or is there a more viable/common approach?