Some programming languages like e.g. Scala have the concept of Option
types (also called Maybe
), which can either contain a value or not.
From what I've read about them they are considered widely to be a superior way of dealing with this issue than null
, because they explicitly force the programmer to consider the cases where there might not be a value instead of just blowing up during runtime.
Checked Exceptions in Java on the other hand seem to be considered a bad idea, and Java seems to be the only widely used language that implements them. But the idea behind them seems to be somewhat similar to the Option
type, to explicitly force the programmer to deal with the fact that an exception might be thrown.
Are there some additional problems with checked Exceptions that Option
types don't have? Or are these ideas not as similar as I think, and there are good reasons for forcing explicit handling for Options and not for Exceptions?
Best Answer
Because
Option
s are composable. There are a lot of useful methods onOption
that allow you to write concise code, while still allowing precise control on the flow:map
,flatMap
,toList
,flatten
and more. This is due to the fact thatOption
is a particular kind of monad, some objects that we know very well how to compose. If you did not have these methods and had to pattern match always onOption
, or callisDefined
often, they would not be nearly as useful.Instead, while checked exceptions do add some safety, there is not much you can do with them other than catching them or let them bubble up the stack (with the added boilerplate in the type declaration).