2 ms·
What advantage does this approach give over Java's checked exceptions, which have support built right into the language already?
by shawnz 7y ago
What advantage does this approach give over Java's checked exceptions, which have support built right into the language already?
- joshlemer 7y agoNot saying using Either is pure win, but I think a lot of the benefits of the approach is that it's a lot more flexible for different actions you may want to take in response to errors. If you can reify the "throwing an exception" action as data (in this case, `Left(error)` then you can very easily for instance collect a bunch of these errors in a list or something, or perform other transformations. Or maybe you have a collection of data to perform work on, and only on the data that was associated with an error do you want to report, and the data that was not associated with an error, you want to process normally. It may be hard to write code that's flexible enough for all of these use-cases in a style that deals with errors by throwing exceptions up the call stack, but your mileage may vary.
- darkkindness 7y agoEither and try-catch are basically the same thing, except try-catch is, as you say, baked into the language, while Either is just data, a value you can manipulate however you want. Usually they will have the same functionality, but in some cases Either gives a few distinct advantages (off the top of my head): - You can work a list of Either values (Lefts and Rights). For example applying a readFile operation on a list of file paths can give you a list of Lefts (errors) or Rights, which you can handle later. I can't imagine doing that cleanly with try-catch (i.e. without building up some intermediate list). - Can return whatever data you want in the error, rather than just a String message (or, I guess you can if you write some custom CheckedException, but Either saves you from having to do that every time)