Beginning in Scala and reading about Either I naturally comparing new concepts to something I know (in this case from Java). Are there any differences from the concept of checked exceptions and Either?
In both cases
- the possibility of failure is explicitly annotated in the method (
throwsor returningEither) - the programmer can handle the error case directly when it occurs or move it up (returning again an
Either) - there is a way to inform the caller about the reason of the error
I suppose one uses for-comprehensions on Either to write code as there would be no error similar to checked exceptions.
I wonder if I am the only beginner who has problems to see the difference.
Thanks
Eithercan be used for more than just exceptions. For example, if you were to have a user either type input for you or specify a file containing that input, you could represent that asEither[String, File].Eitheris very often used for exception handling. The main difference betweenEitherand checked exceptions is that control flow withEitheris always explicit. The compiler really won’t let you forget that you are dealing with anEither; it won’t collectEithers from multiple places without you being aware of it, everything that is returned must be anEither, etc.. Because of this, you useEithernot when maybe something extraordinary will go wrong, but as a normal part of controlling program execution. Also,Eitherdoes not capture a stack trace, making it much more efficient than a typical exception.One other difference is that exceptions can be used for control flow. Need to jump out of three nested loops? No problem–throw an exception (without a stack trace) and catch it on the outside. Need to jump out of five nested method calls? No problem! Either doesn’t supply anything like this.
That said, as you’ve pointed out there are a number of similarities. You can pass back information (though
Eithermakes that trivial, while checked exceptions make you write your own class to store any extra information you want); you can pass theEitheron or you can fold it into something else, etc..So, in summary: although you can accomplish the same things with
Eitherand checked exceptions with regards to explicit error handling, they are relatively different in practice. In particular,Eithermakes creating and passing back different states really easy, while checked exceptions are good at bypassing all your normal control flow to get back, hopefully, to somewhere that an extraordinary condition can be sensibly dealt with.