Hello everyone,
Exceptions in OCaml have the reputation of being very fast. As a result, it’s common to use them to signal errors and they are also recommended for advanced control flow. But what’s really happening at runtime? Which low-level operations are executed when we raise and catch an exception at the assembly level? Are they really that fast?
For someone like me who enjoys the comfort of a high-level language, these are quite obscure questions: I’ve no idea of what’s really happening once it’s been compiled! (and I wouldn’t be able to discover this on my own)
This is why I absolutely loved Fabrice Buoro @fabbing’s presentation on how the OCaml runtime represents and handles exceptions. His talk has recently been uploaded on watch.ocaml.org:
OCaml behind the scenes: Exceptions
While understanding this talk requires you to know how to use exceptions (raise
and try with
), that’s the only requirement! This is quite an amazing feat as Fabrice explains the assembly, low-level representation and OCaml stack in great details… so I guess the other requirement is that you are willing to suspend your disbelief and discover that you can actually understand this dark magic with the right explanation Besides the satisfaction of learning how it works and acquiring the associated performance knowledge, it’s also a great teaser for the implementation of OCaml 5 effect handlers: I hope it will inspire you to look at other parts of the runtime, as we don’t talk often enough about why OCaml is so efficient.
Bonus: The talk contains a lot of beautiful Tikz illustrations which had me amazed. But how those diagrams were created is even more incredible, as Fabrice wrote code to generate them from running gdb
on real OCaml programs: GitHub - fabbing/obts_exn: OCaml behind the scenes: exceptions Hats off, this is crazy dedication to teaching the real thing <3
If you have any questions, I’m sure @fabbing will be happy to answer them!