How OCaml exception handling works?

Oh, one thing that is worth keeping in mind is that top-level definitions are all executed outside of what you think of as your “main” entry point, and each one could raise an exception, so there’s no “easy” way to really have a “single root try/catch”. So, for all such definitions, you need to do one of:

  1. Be very sure that the top-level expression won’t fail (again, aside from truly unrecoverable stuff like OOM).
  2. Define them to be lazy values, so that when they are accessed from e.g. inside an event loop, anything bad that happens can be caught and reported cleanly.

Alternatively, you could be very judicious in not having such top-level definitions. This is what I do for my most complex applications, where I have explicit lifecycle abstractions for initializing what would otherwise be top-level values, and then ways for the various parts of the app to access those values from some central context.

1 Like