After using F# option
type for a while, I realize that it could be used for handling exceptional cases. I can use either option
or Exception
in the following examples:
find
functions from List/Array/Seq modules raise KeyNotFoundException
in uncommon cases, while corresponding tryFind
counterparts return None
in those situations.My impression is option
is a more functional approach, while Exception
is more commonly-used in the .NET platform.
What are differences between option
and Exception
in exception handling in terms of usability, performance, etc? In which cases using a technique is better than using the other?
The CLR makes the operation of throwing and catching an exception extremely expensive. For this reason alone, you should prefer constructs like Option for reporting expected failures. If the failure is truly exceptional and nearly unrecoverable, go ahead and throw an exception. But as you note, things like backtracking during a search are unexceptional, and you will find your performance suffers greatly if you implement them with exceptions.
Because this is a property of the CLR, it doesn't really matter whether you are in F# or not. My understanding is that other runtimes for ML-like languages, e.g. ocaml, do not have this characteristic, and so may use exceptions more often for control flow.