skip to content

In C++, how does the noexcept specifier differ from the noexcept operator, and what happens when a noexcept function throws?

level: middleimportance: must knowfreq 60%

answer

  1. one declares, one asks
  2. unevaluated, compile-time bool
  3. the declaration, not the body
  4. violation is not a compile error

basics

~20 s

The noexcept specifier declares that a function will not exit via an exception; the noexcept operator is a compile-time query returning whether an expression is potentially throwing. If an exception does reach a noexcept boundary, std::terminate is called; the compiler does not reject it.

solid answer

~40 s

`void f() noexcept;` or `noexcept(constant-expression)` is a **specifier**: part of the function's declaration and, since C++17, of its type. `noexcept(expr)` is an **operator**: its operand is unevaluated and it yields a `bool` constant that is `false` if the expression could throw by the language's rules, which look at declarations, not bodies, so a function that never throws but is not declared `noexcept` still counts as throwing. The two combine in `noexcept(noexcept(std::swap(a, b)))`, a conditional specifier for generic code. A `noexcept` function that throws is still well-formed: when the exception reaches its boundary, `std::terminate` is called, and whether the stack is unwound first is implementation-defined. Clang warns with `-Wexceptions` when it sees an obvious throw inside one.

code

cpp · 29 lines
cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

struct Item { std::string sku; int qty = 0; };

std::size_t count_items(const std::vector<Item>& v) noexcept { return v.size(); }
int  twice(int n) { return 2 * n; }                      // never throws, not declared so
void add_item(std::vector<Item>& v, const Item& i) { v.push_back(i); }

template <class T>
void swap_slots(T& a, T& b) noexcept(noexcept(std::swap(a, b))) { std::swap(a, b); }

void restock(int qty) noexcept {
    if (qty < 0) throw std::invalid_argument("negative quantity");  // compiles, warns
}

int main() {
    std::vector<Item> inv;
    Item a{"A-1", 3}, b{"B-2", 5};
    std::cerr << std::boolalpha
              << noexcept(count_items(inv)) << ' '   // true
              << noexcept(twice(1)) << ' '           // false: only the declaration counts
              << noexcept(add_item(inv, a)) << ' '   // false
              << noexcept(swap_slots(a, b)) << '\n'; // true with std::allocator strings
    restock(-1);                                     // std::terminate
}

go deeper

for a junior

Know that noexcept marks a function as not throwing and that throwing anyway ends the program through std::terminate.

for a middle

Separate the specifier from the operator, explain that the operator is unevaluated and reads declarations only, and write the conditional noexcept idiom.

for a senior

Diagnose a production std::terminate traced to a noexcept boundary, knowing destructors in between may not have run, and use -Wexceptions plus type traits to catch it earlier.

for a principal

Treat noexcept as a permanent interface promise: removing it later can change callers' code paths, so set a rule for when the team may add it.

## Two uses of one keyword C++ uses `noexcept` in two grammatically different places: - As a **noexcept-specifier** after a function declarator: `noexcept` alone means `noexcept(true)`, and `noexcept(constant-expression)` takes a constant expression contextually converted to `bool`. A `false` value, or no specifier at all on an ordinary function, gives a **potentially-throwing exception specification**. - As a **noexcept-expression** inside an expression: `noexcept(expression)` is an operator whose operand is **unevaluated**, like `sizeof`. Its result is a `bool` prvalue and an integral constant expression. ## What the operator inspects The operator returns `false` when the full-expression of its operand is **potentially-throwing**. The standard defines that syntactically: - a call to a function whose type has a potentially-throwing exception specification; - an implicit call to such a function: an overloaded operator, the allocation function of a `new`-expression, a constructor for a function argument, a destructor; - a `throw`-expression; - a `dynamic_cast` to a reference type that needs a run-time check, or `typeid` applied to a dereferenced pointer to a polymorphic type; - any non-unevaluated subexpression that is potentially-throwing. The operator never looks inside a function body. In the snippet below `twice(int)` cannot throw, yet `noexcept(twice(1))` is `false`, because its declaration does not say `noexcept`. ## The conditional `noexcept` idiom Generic code cannot know whether its operations throw, so it asks: ```cpp template <class T> void swap_slots(T& a, T& b) noexcept(noexcept(std::swap(a, b))); ``` The outer `noexcept(...)` is the specifier; the inner one is the operator. The function is `noexcept` exactly when the `swap` it performs is. Standard type traits such as `std::is_nothrow_destructible_v<T>` and `std::is_nothrow_swappable_v<T>` package the same question. ## What happens on a violation A `noexcept` specifier is **not checked at compile time**. The standard even forbids rejecting a program merely because a non-throwing function might throw. At run time, if the search for a handler would leave the body of a function with a non-throwing exception specification, **`std::terminate` is called**. For this case the standard makes it implementation-defined whether the stack is unwound fully, partially or not at all before that call, so destructors in the frames between the `throw` and the `noexcept` boundary may never run. Clang catches the obvious cases. On `void restock(int qty) noexcept { if (qty < 0) throw ...; }` clang 21 printed: ```plaintext warning: 'restock' has a non-throwing exception specification but can still throw [-Wexceptions] ``` It cannot see a throw buried in a called function, which is the usual way this bug reaches production. ## Rules that interviewers check 1. **Part of the type since C++17.** A pointer to a `noexcept` function converts to a pointer to a potentially-throwing one, not the reverse. 2. **Virtual functions.** If a base virtual function is non-throwing, every override must be non-throwing too, unless the override is deleted. 3. **Old syntax is gone.** Dynamic exception specifications like `throw(std::bad_alloc)` were removed in C++17, and `throw()` in C++20; `noexcept` replaces both. 4. **Implicit specifications.** Destructors and special members defaulted on their first declaration get an exception specification computed from the functions they would call, which for destructors is usually `noexcept(true)`; a deallocation function without a specifier is non-throwing. ## Details that change the operator's answer - **Temporaries count.** If the operand is a prvalue, the temporary is materialized, so its destructor is part of the question: for a function `Flaky make() noexcept;` returning a type whose destructor is `noexcept(false)`, `noexcept(make())` is `false`. - **Implicit calls count.** An overloaded operator, a converting constructor for an argument, or the allocation function in a `new`-expression each make the expression potentially throwing if they are. - **Lambdas and defaulted members.** A lambda takes a specifier after its parameter list, `[](int n) noexcept { return n; }`, and a special member defaulted on its first declaration gets one computed from the members it calls. - **Nothing is evaluated.** `noexcept(add_item(inv, a))` calls nothing and adds nothing to the inventory, exactly like `sizeof`. ## When to write the specifier Mark a function `noexcept` when it genuinely cannot fail and you are willing to keep that promise in every future version, because callers can test it with the operator and pick faster code paths. Leave it off when the function can fail, even rarely; a `noexcept` function that allocates turns `std::bad_alloc` into `std::terminate`.

  • Why does noexcept(twice(1)) return false for a function that obviously cannot throw?
    The operator applies the standard's definition of a potentially-throwing expression, which looks only at declared exception specifications. A call to a function declared without `noexcept` is potentially throwing whatever its body does. This keeps the answer stable across translation units, where the body may not even be visible; if the function cannot fail, declaring it `noexcept` is how you tell callers.
  • Can an override drop the noexcept of the virtual function it overrides?
    No. If the base function has a non-throwing exception specification, every declaration of an overriding function must also be non-throwing, unless the override is defined as deleted; otherwise the program is ill-formed. The reverse is allowed: an override may add `noexcept` to a potentially-throwing base function, since it promises more.

  • The compiler rejects a noexcept function that contains a throw.
  • noexcept(f()) returns true when f's body never throws.
  • A throw from a noexcept function always unwinds the stack before terminating.
  • noexcept is just documentation and changes nothing at run time.
  • throw() is the C++20 way to declare a non-throwing function.

Assumes C++17 or later: noexcept is part of the function type since C++17, dynamic exception specifications were removed in C++17 and throw() in C++20.