Exceptions vs Option


What of methods is more preferable:

match f () with
| Some x -> …
| None -> …


match f () with
| x -> …
| exception Not_found -> …

And in general. If there will be algebraic effects in OCaml whether we have to stop using monads? Ocaml allows to write a code in any style,
but it seems to me that it is good to have the conventional standards.

Matching on exceptions means you are giving up the help of the compiler to do exhaustiveness check. In the first one, if you don’t add | None -> clause, the compiler will complain that your match clauses are not exhaustive. AFAIK the second one will not if you missed the | exception Not_found -> clause.

I will not speak for conventional standards, since I’m not sure whether there’s any, but in general I think it is desirable to strive for using option in this case.

In a more general case, for modeling an operation that may fail, it’s better to use result instead of option, and only use option if the data strictly either exists or does not exist.

What’s more, using monads will make it easier to chain operations later on (via map, bind, etc.)


This recent post on r/ocaml explores 4 ways to handle errors in OCaml. An interesting reading.


Thanks a lot for very detailed and clear answer.

Possibly, the second part of my question is too abstract.
And I understand that hardly anyone that will be able to tell something certain now.

I meant what I don’t understand as monads and effects will coexist together.
(IMHO, Option is something from monadic world).
I.e. if effects will be accepted in OCaml, then, perhaps,
something like following constructions will be used:

match f() with
| x -> …
| effect NotFound k -> …

And, looking in the future whether we have to adapt to new reality gradually?