# Use noexcept for Exception Handling in C++ Programs

## Introduction

The noexcept specifier was introduced in C++ standard 11. Its explanation is also very straightforward. It specifies whether a function could throw exceptions.

I actually did not quite understand why we would like to prevent a program from throwing exceptions. In this blog, I am going to describe how noexcept could be used to protect C++ programs from undesired behaviors.

## Example

It turns out that some functions, especially some black box functions from libraries, would cause memory leak when an exception is thrown. The getArraySum function, which is a weird orchestrated function, in the following code is such a example.

To prevent the undesired memory leak from happening, instead of using the getArraySumWarraper function, we would like to use the getArraySumWarraperNoexcept function with the noexcept specifier. When getArraySumWarraper is called, the program would never crash, but potentially have the risk of memory leak. When we call getArraySumWarraperNoexcept, the program crashes whenever there is an exception thrown from getArraySum.

To compile the program, run the following command in the terminal.

We use Valgrind to check whether the program has memory leak or not.

If we input three numbers 1, 2, and 3, we don’t have memory leak for the program with or without using the noexcept specifier.

If we input three numbers 100, 200, and 300, we are supposed to have memory leaks for the programs. As we can tell from the Valgrind results, without using the noexcept specifier, there is memory leak as expected. However, with using the noexcept specifier, the program would just crash (std::terminate will be called).

## Conclusions

The noexcept specifier protects C++ program from memory leaks and potentially other undesired behaviors, such as vector growth using move operations, brought by throwing exceptions. For key functions we hardly know how to handle its exceptions, it might be a good idea to add the noexcept specifier.

Use noexcept for Exception Handling in C++ Programs

https://leimao.github.io/blog/noexcept-Specifier-CPP/

Lei Mao

12-31-2019

12-31-2019