We've experimented with checked exceptions to represent business errors in our Java domain model lately. Business errors are now a represented as a first class thing in the code and they are visible at the type level. This has lead to several advantages, most notably (1/x)
many discussions with business regarding error messages and how to handle certain errors that we didn't anticipate while doing event storming and other types of interactive modelling. It has also lead us to spot several bugs before they reached production. There are (2/x)
obviously huge drawbacks of checked exceptions in Java as well. Most notably the fact that you cannot use the Stream API and delegate the exception handling to a later stage. To get around this we also tried experimenting with monad containers such as Either, Validation, etc(3/x)
but this becomes very messy in Java pretty fast. Especially when combined with proper value objects, that can have business errors on initialization, since Java doesn't support for-comprehensions. The code also looks strange to the average Java developer. Maybe this (4/x)
will be better in the future with fibers? The nice thing with exceptions in Java is that they compose; i.e. if you call two methods that throw different exceptions you are forced, at compile-time, to handle ALL exceptions (or re-throw them). This is not possible to (5/x)
achieve (afaik) using other means in Java (for example by using some sort of ADT). I'm not sure whether or not we'll continue using checked exceptions in the future, but it has been an interesting experience worth considering. Might write up a blog post in the future :) (6/6)
You can follow @johanhaleby.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: