Search code examples
.netexceptionf#option-type

Option vs Exception in exception handling


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:

  1. The find functions from List/Array/Seq modules raise KeyNotFoundException in uncommon cases, while corresponding tryFind counterparts return None in those situations.
  2. When I do backtracking (in solving N-queens, Sudoku, etc), whenever a branch has no solution, I can either raise an exception and catch it later or return None to match that value to backtrack. Those cases occur quite often until we find a solution.

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?


Solution

  • 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.