Universally, exceptions are avoided in embedded systems C++ code, with a preference for error codes as out parameters, return values, or sum types like std::expected<T,E>. This avoidance stems from two main issues: the size of the exception handling runtime and the performance cost of throwing an exception versus returning a status code. But what if I were to tell you that exceptions are the better choice for producing smaller binaries than using the alternatives?
In this talk, I will explore the space cost of exceptions on a Cortex M4 microcontroller using the ARM GNU Toolchain, how to reduce the space cost, compare it to result types and identifying the point where result types become more costly in terms of code size than exceptions. I will delve into the performance of exceptions on the same Cortex M4 microcontroller, demonstrating how I managed to cut the cycle count in half. I’ll offer suggestions for improving exception performance on the sad path and explain how exceptions enhance performance on the happy path. Finally, I’ll share why, after 11 years in embedded systems, 7 years teaching embedded systems, and 6 years in professional consumer electronics, I now believe that exceptions are the superior error handling mechanism for embedded systems.