[WATCH] OCaml behind the scenes: Exception

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 :slight_smile: 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!


To celebrate this talk now being publicly available, I’ve added a chapter that was not part of the original presentation!

This Backtraces section aims to explain how backtraces are constructed for exceptions, so that exceptions can be linked to the code location that raised them. It also gives enough details about the implementation to justify the claims in Takeaway #5 about backtrace collection and raise_notrace.

It’s a bit technical, so I didn’t dive in all the details, but there’s certainly plenty to understand the technique used.

The updated slides can be found in the release page of the repository: Releases · fabbing/obts_exn · GitHub
Feel free to ask me any questions if anything isn’t clear enough. :slightly_smiling_face: