Exceptions

nothrow new: the Variant to Use When Avoiding C++ Exceptions

I'm a relatively young C++ developer, having spent the majority of my career programming in C. While I've devoted myself to the study of the language, I still frequently learn about new features and capabilities that surprise me.

I recently learned about nothrow new, a version of the new operator which returns a nullptr on failure instead of throwing an exception. While I have never seen this new operator usage in the wild, it's a valuable addition to my toolkit, as I often write embedded C++ programs without exceptions enabled.

In order to use the std::nothrow variants of new, you need to include the <new> header. Then you can overload new with std::nothrow:

int32_t* buffer = new (std::nothrow) int[100000000ul]; //non-throwing overload

If your system cannot allocate the memory, new will return nullptr rather than throwing std::bad_alloc.

Further Reading

CException: Simple Exception Handling in C

CException is a project released by Throw The Switch. CException is designed to provide simple exception handling in C using the familiar try/catch/throw syntax. I've been recently thinking about the downsides of error logging, so I am excited to see a lightweight exception library for C.

The exception implementation is kept simple by only allowing you to throw a single error code. No support for throwing objects, structs, or strings is included. The library can be configured for either single-tasking or multi-tasking which makes this project a good fit for embedded systems using an RTOS. CException is implemented in ANSI C and is highly portable. As long as your system supports the standard library calls setjmp and longjmp, you can use CException in your project. If you're looking for an exception library to use on embedded systems, CException is for you.

Further Reading

For more on CException:

A Warning When Using -fno-exceptions

As an embedded C++ developer, I typically write programs with exceptions disabled. My typical method for accomplishing this is by using the -fno-exceptions compiler flag. Unfortunately, I never realized a very important detail: even if I compile with -fno-exceptions, the C++ libraries I'm using have not been compiled with -fno-exceptions.

In order to be truly safe under this condition, I would need to avoid any standard library functions which might throw an exception, because they still will throw even if I cannot catch.

While some compilers, such as Keil, will correctly link a C++ library variant with exceptions disabled, this behavior is not guaranteed. If you are unsure whether a different library is being linked, I recommend compiling the C++ runtime with exceptions disabled. In this case, throw calls will be replaced with abort, which should be defined appropriately for your system.

Further Reading