r/cpp_questions • u/Loose_Low8543 • 14h ago
OPEN Why are exceptions so "backstabby"?
Simply put, I often find myself being told that exceptions "are not that costly" and that "the compiler puts it on cold sections anyways".
As a forenote, I'm the kind of person who always does `-fno-rtti -fno-exceptions` as I value code size usage (I develop small embedded shit and such, which does lead me to decorate functions with alignas and other thingies). Sometimes I also drop using the libc/libc++ and do syscalls raw because I can't stand the overhead (malloc/operator new is a great general purpouse allocator, but it doesn't suit my specific performance needs for example), so I take the hit from doing a syscall for a big mmap and then manually allocate memory by using fixed upper bounds.
(Ok also because glibc malloc sucks, but that is another topic)
Now with that noted, I have one pique in life: Why should I even use exceptions?
I often find myself removing exceptions of whatever codebase I happen to contribute to. Which does lead to people telling me that "you shouldn't do that".
The reason they often cite is either:
- It's not that important in the grand scheme of things (Valid, but so is every 'death by a thousand cuts')
- It makes code less clear (I'd argue otherwise)
- It's standard/idiomatic (Yeah and so is std::auto_ptr)
I really want to know WHY should I even use exceptions. I feel like they're a waste of language grammar I'm forbidden for touching, for it would bring me great despair.
As a cited case; recently I was working on optimizing a JSON parsing loop (oh scary). Obviously the final solution was not using JSON and just doing raw text with the |0x202020 casecmp trick.
But after collecting the values on a vector (I'd rather prefer a VLA to avoid indirection btw) I saw that the specialization of the vector for the non trivial class did in fact make a bunch of garbage for a case that I would have not hit otherwise.
https://godbolt.org/z/MPb9xnYqx
Like this is dumb, I'm not developing code for an airplane, if the thing runs out of memory it's just gonna crash anyways.
And no, noexcept also sucks because it just wraps shit around {} with std::terminate(), which is dumb (atleast on MSVC, but whatever).