Why are exceptions and RTTI often disabled in embedded C++?
Short answer: Exceptions add unwind tables and support code (often tens of KB of flash), make worst-case timing hard to bound (unwinding cost depends on the call stack), may allocate memory for the exception object, and add hidden control-flow paths that safety standards dislike. RTTI (typeid, dynamic_cast) adds type-information tables for every polymorphic class. Many teams compile with -fno-exceptions -fno-rtti and use error codes, std::optional, or std::expected (C++23, or a small equivalent) instead.
Error handling without exceptions
#include <cstdio>
#include <optional>
enum class Err { Timeout, Nack, Range };
template <typename T>
struct Result { // tiny expected-like type
bool ok; T value; Err err;
static Result success(T v) { return { true, v, {} }; }
static Result failure(Err e) { return { false, T{}, e }; }
};
Result<int> read_temp(bool sensor_present)
{
if (!sensor_present) return Result<int>::failure(Err::Nack);
return Result<int>::success(23);
}
std::optional<int> parse_digit(char c)
{
if (c < '0' || c > '9') return std::nullopt;
return c - '0';
}
int main()
{
auto r = read_temp(false);
if (!r.ok) std::printf("error %d\n", static_cast<int>(r.err)); // error 1
std::printf("%d\n", parse_digit('7').value_or(-1)); // 7
}
Mark result types [[nodiscard]] so ignoring an error produces a compiler warning.
Consequences of -fno-exceptions
newthat fails must not throw: usenew (std::nothrow)and check for null, or avoidnew.- Standard library functions that would throw call
std::abort()(or a terminate handler) instead — e.g.std::vector::atout of range; provide your ownaborthandler that logs and resets. - Third-party libraries that rely on exceptions cannot be used as is.
When exceptions are acceptable: larger embedded Linux applications, or MCUs with plenty of flash where the team decides the timing impact is acceptable for rare error paths. Modern compilers have "zero-cost" (table-based) exceptions with no cost on the non-throwing path, but the size and worst-case cost remain.