4 ms·
It's arguable that this is a programming bug an not really recoverable, so throwing doesn't make much sense. You can be defensive to various degrees about asse
by steerablesafe 6y ago
It's arguable that this is a programming bug an not really recoverable, so throwing doesn't make much sense.
You can be defensive to various degrees about assertions:
1. You can just use assert() to fail in Debug and do nothing in Release.
2. You can be more defensive and define your always_assert() to fail in Release as well.
3. You can double down on the UB with hints to the compiler and provide assume(), which explicitly compiles to UB when it's triggered in Release (using __builtin_unreachable() for example).
About the organization of the if statement: I agree that the former is better, I would use assert(false) though.
- mytherin 6y agoIndeed it is a programming bug - but programming bugs happen. In my experience writing programs as if bugs will not happen is typically a bad idea :) Throwing an exception here is basically free (just another switch case) and gives the user a semi-descriptive error message. When they then report that error message I can immediately find out what went wrong. Contrasting with a report about a segfault (with maybe a stacktrace), the former is significantly easier to debug and reason about. assert_always would provide a similar report, of course. However, as we are writing a library, crashing is much worse than throwing an internal error. At worst an internal error means our library is no longer usable, whereas a crash means the host program goes down with it.