Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Practical C++ Error Handling in Hybrid Environments


Exception-safe code is notoriously difficult to get right in C++. Still, it is the recommended way to go, at least according to C++ gurus. And for a reason. If you write nontrivial programs or libraries in C++, you should probably study exception handling and use it where appropriate.

In the real world, however, exception handling is not always possible, viable, or used by anyone. So what do you do if you need to integrate or interoperate with software that doesn't use exception handling? In this article, I discuss situations where exception handling is not used and why. I then demonstrate how to interface your exception-handling code to other software components that practice a different error-handling method.

Error-Handling Strategies in C++

There are different ways to report and handle errors in C/C++. (You have to consider C because C++ is—more or less—a superset of C and often C++ programs link against C libraries, libraries that expose C APIs, call C code, and are called from C code via global/static functions or function pointers.)

Exceptions are the official error-handling mechanism, of course. However, C++ was initially designed without exceptions and it shows. For example, IO streams don't throw exceptions by default, but set a "fail" bit when something goes wrong. Compilers, being backward-compatible creatures, usually provide switches to turn exception handling on/off. This means that if you call new and run out of memory, you either get a NULL pointer or an std::bad_alloc exception.

Status/Return codes are another error-handling technique. This is as simple as it gets and provides the lowest common denominator that is always available, even if you port your code to different languages. Status/Return codes foster visibility in the source code of the path of specific errors but at the price of clutter.

setjmp/longjmp is an early C language stack-unwinding exception handler that is widely used to handle input errors detected by deeply nested function calls, such as the recursive descent parsing algorithms of source code language translators. Like C++ exception handling, setjmp/longjmp eliminates the need to know about and handle error return codes all the way up the recursive ascent. Unlike the C++ try/catch mechanism, which has to destroy automatic objects along the way up, setjmp/longjmp adds very little runtime and space overhead to a program.

Likewise, errno is yet another C error mechanism. It is just a global object that can contain an error code. It is not thread-safe so its raw usage is discouraged in concurrent systems.

Managed Environments/Proprietary Error-Handling Mechanisms

Because Microsoft is the only vendor that provides deep integration to operating system facilities (SEH) or managed environments (COM and CLR) at the C++ level, all of the following mechanisms are Windows specific. This is an important trend. The Mono runtime brings .NET to the cross-platform world, and while it doesn't yet provide a C++ front-end, there is work towards it. All of these error-handling mechanisms integrate and interoperate with each other and with C++ exceptions to some degree.

Get/Set LastError is a glorified errno for Win32. It's better than errno in the sense that code in other languages can access it through the Windows API. Cross-language, as opposed to cross-platform, code is a big concern of Microsoft.

Win32 Structured Exception Handling (SEH) is the low-level OS mechanism that calls a certain callback when some thread faults. The Visual C++ compiler wraps it for you and implements the C++ exception model on top of it. You can ignore it most of the time, just know that it's there in the bizarre case you need to dig that deep and find out something.

COM/ATL error handling is a different beast. COM was designed to be language agnostic. As such it couldn't rely on any language's error-handling facilities. So, COM came up with its own error-handling facility. COM has an error object that is accessible via various COM interfaces: ICreateErrorInfo for creating error objects, IErrorInfo for accessing error information, and ISupportErrorInfo to check if a certain COM class actually creates instances of the error object. The punch-line is that I don't really know how ubiquitous the COM error object is. When I used COM/ATL a lot, I used plain HRESULTs, which is equivalent to C status/return codes.

In terms of managed (.NET/CLR) exceptions, the .NET/CLR assimilates, subsumes, and encapsulates all other Windows technologies. It provides its own exception model and specific CLR extensions for C++, but also has a unique mechanism for interfacing with pure C++ code. It reportedly just works most of the time. I've never used it.

When Exceptions Are Not Used (And Why)

There are two metareasons for not using C++ exception handling:

  • You can't. This includes C code (or code that's exposed through a C API), code that runs in some managed environment, and legacy systems built using a compiler that doesn't support exceptions properly or not in a cross-platform way.
  • You don't want to (or the powers that be don't want to). This includes performance-critical systems where you don't want to pay the overhead of exceptions. It also includes uncomfortable developers who don't want to mess with exceptions in the first place, or the desire to have a single error-handling mechanism across the system.

C++ is the only language I'm aware of that even lets you turn exception handling on/off. In other languages, you either have exceptions or you don't. You can use other mechanisms if you want, but exceptions are there and runtime failures probably trigger exceptions, so you must be ready to catch them.

If you develop code that you want other people to use, you would be wise to consider exposing it through a C API. The C++ Application Binary Interface (ABI) is not part of the C++ Standard. Every compiler vendor changes it with every major version (and sometimes more often). The result is that you can't statically link a C++ library if it was compiled using a different compiler. It is also not possible on a nonWindows platform to load C++ classes directly from a dynamic library. So, if you are not in the business of shipping source distributions and you want to reach a larger audience than people who happen to have exactly your compiler, stick to C.

With managed environments, you don't even have the choice. If your code must run in a managed environment, you must play by its rules. There isn't much point in throwing an uncaught exception in your COM out of a process module. It would never make it across to the calling code without marshalling.

Legacy systems can be big, yet fragile, creatures. The smallest change might break them, they may rely on undocumented APIs or bugs in a specific compiler implementation. Upgrading the compiler or changing the error-handling strategy is typically prohibitively expansive. Chances are you won't be able to persuade the powers that be to upgrade the compiler and potentially destabilize the system just so you can use cool C++ exceptions in your shiny new module.

Exception handling has a runtime overhead, even when exceptions are not thrown. The compiler needs to manage a list of all the stack objects that were constructed to call their destructors when an exception is thrown. This implies at least a space overhead (if the list is prepared during compilation). If the preparation of this list is done at runtime, then there is also a time overhead. Many performance-critical systems have a shoestring budget for CPU cycles and memory bits, and developers can't afford the cost of exception handling.

In general, C++ developers, who are considered hard-core in comparison to other developer, are uncomfortable with C++ exception handling due to the complexity of implementing it correctly. Exception handling in other languages that support garbage collection (Java, Python, C#) is much simpler and developers have no problem using it. Still, exceptions have a lot going for them. They can considerably simplify error handling in C++ programs. However, they are not simple by themselves. Many developers just know that getting C++ exceptions to work is complicated. Many experienced C++ developers never used exceptions in their code because they only worked on projects that fall under the aforementioned restrictions or they learned C++ before exceptions were introduced to the language. In the initial meeting of a new project when it's time to pick an error-handling strategy, inexperienced developers tend to stick to what they know. Exception handling is not as cool as templates, so developers often don't feel that they "have" to use it, just because they never used it before.

Software is complicated. When system architects face crucial decisions such as picking an error-handling strategy, they often prefer a single mechanism instead of two that have to interact. Since many libraries and existing code bases don't leverage exceptions, this single mechanism is often a simple return code, or one of the other nonexceptional mechanisms.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.