C++ exception overhead

Yippie-Ki-Yay picture Yippie-Ki-Yay · Jul 13, 2011 · Viewed 8.6k times · Source

Why do embedded platform developers continuosly attempt to remove usage C++ exceptions from their SDKs?

For example, Bada SDK suggests the following workaround for the exception usage, which looks exceptionally ugly:

 result
 MyApp::InitTimer()
 {
    result r = E_SUCCESS;

    _pTimer = new Timer;

    r = _pTimer->Construct(*this);
    if (IsFailed(r))
    {
        goto CATCH;
    }

    _pTimer->Start(1000);
    if (IsFailed(r))
    {
        goto CATCH;
    }

    return r;
 CATCH:
     return r;
 }

What are the reasons for this behavior?

As far as I know, ARM compilers fully support C++ exceptions and this couldn't actually be the matter. What else? Is the overhead of the exception usage and unwindings on ARM platforms really that BIG to spend a lot time making such workarounds?

Maybe something else I'm not aware of?

Thank you.

Answer

Dan picture Dan · Jul 13, 2011

Just my 2 cents...

I consult exclusively on embedded systems, most of them hard real-time and/or safety/life critical. Most of them run in 256K of flash/ROM or less - in other words, these are not "PC-like" VME bus systems with 1GB+ of RAM/flash and a 1GHz+ CPU. They are deeply embedded, somewhat resource-constrained systems.

I would say at least 75% of the products which use C++ disable exceptions at the compiler (i.e., code compiled with compiler switches that disable exceptions). I always ask why. Believe it or not, the most common answer is NOT the runtime or memory overhead / cost.

The answers are usually some mix of:

  • "We're not confident that we know how to write exception safe code". To them, checking return values is more familiar, less complex, safer.
  • "Assuming you only throw an exception in exceptional cases, these are situations where we reboot anyway [via their own critical error handler routine]"
  • Legacy code issues (as jalf had mentioned) - they're working with code that started out many years ago when their compiler didn't support exceptions, or didn't implement them correctly or efficiently

Also - there is often some nebulous uncertainty/fear about overhead, but almost always it's unquantified / unprofiled, it's just kind of thrown out there & taken at face value. I can show you reports / articles that state that the overhead of exceptions is 3%, 10%-15%, or ~30% - take your pick. People tend to quote the figure that forwards their own viewpoint. Almost always, the article is outdated, the platform/toolset is completely different, etc. so as Roddy says, you must measure yourself on your platform.

I'm not necessarily defending any of these positions, I'm just giving you real-world feedback / explanations I've heard from many firms working with C++ on embedded systems, since your question is "why do so many embedded developers avoid exceptions?"