by vodou · 2y ago · 0 comments
Since these are "guidelines for the use of C++17 in critical systems", I would have expected it to prohibit exceptions due to their non-determinstic nature. On a side note, dynamic memory is prohibited (rule 21.6.1).
I haven't read the earlier MISRA C++ guidelines so I don't know if this have changed.
I think if you disallow exceptions you run into other problems. How can a constructor fail now? You need to have some kind of flag showing if an object is fully constructed. But then that goes against the idea to "make illegal states unrepresentable".
I do wish C++ had more tools to reign in exceptions. Maybe an "onlythrows X" annotation that says only these very specific exceptions may escape from a block, and the checker will complain if it cannot prove that only X can be thrown. The opposite of checked exceptions basically.
Simply passing by value can result in a constructor that fails, while still bypassing any of the factory functions.
If the copy constructor can fail and you don't want that, then delete it?
I don't understand why jupp0r is getting downvoted?
Most big public c++ projects turn off exceptions, so it seems to be the norm more than anything.
Resource exhaustion or hardware failures are the more straightforward use cases for exceptions, but doing anything clever in those cases requires writing similar handling code as you would without exceptions.
Just crash the system and reboot the MCU can make sense depending on the application. And where it can't, you need to take the same kind of care for handling every single problem at the call site, or correctly propagating it to a layer that can handle it.
Exceptions aren't special here, they are simply a way to do error handling and recovery.
It's the kind of rule that doesn't make sense for applications, but when you've got tightly constrained memory limits, it makes sense.
Almost all systems to which MISRA apply have watchdogs, and crashing to let the watchdog restart the program is a common pattern.
Given that constraint, they conclude that the overhead of maintaining exception unwinding and the non-local control flow aren't worth it.
(To my memory though, Google didn't throw away the benefits of RAII without allowing exceptions... They discouraged complicated behavior in constructors and so the only thing a constructor could fail on was OME, which was supposed to crash anyway).