Partial match: Style advice

Interesting!

I found another source comparing assert false and failwith …: The docs on error handling, section “Assertions”:

Writing assert false would just stop your program. This idiom is sometimes used to indicate dead code, parts of the program that must be written (often for type checking or pattern matching completeness) but are unreachable at run time.

[…]

When the execution reaches conditions which can’t be handled, the right thing to do is to throw a Failure, by calling failwith "error message". Assertions aren’t meant to handle those cases.

(Side note: I think maybe it should read “unreachable code”, not “dead code” above.)

So to my understanding it’s like this now:

  • Use assert false for unreachable code, i.e. code that should (if the program is written correctly) never be reached.
  • Use failwith … for conditions that can’t be handled, e.g. not-yet-implemented requests.

The difference would be: assert false shall never be reached (and in theory the compiler could even use that for optimization when assertion checks are disabled, even though OCaml doesn’t do that). In contrast, failwith …, is more like a generic run-time exception. Something that can actually happen and needs to raise an error.

I would probably consider using failwith … when I depend on behavior of a third-party library. I.e. in the example of my original post, if function g was a library function, then this seems to be a nice choice:

But if g and f are part of the same code section, maybe even in the same function, then assert false seems to be the better choice to me.