# noexcept

> The noexcept specifier is a promise that a function will not let an exception escape, enforced at run time by std::terminate rather than at compile time. The noexcept operator asks whether an expression could throw, and since C++17 the promise is part of the function type.

- **Source:** C++ Atlas (https://cppatlas.com/topics/noexcept)
- **Track:** Exceptions and error handling
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [except.spec] (https://eel.is/c++draft/except.spec), [expr.unary.noexcept] (https://eel.is/c++draft/expr.unary.noexcept), [conv.fctptr] (https://eel.is/c++draft/conv.fctptr), [except.terminate] (https://eel.is/c++draft/except.terminate), [class.dtor] (https://eel.is/c++draft/class.dtor), [dcl.fct.def.default] (https://eel.is/c++draft/dcl.fct.def.default), [res.on.exception.handling] (https://eel.is/c++draft/res.on.exception.handling)
- **cppreference links:** [noexcept specifier](https://en.cppreference.com/w/cpp/language/noexcept_spec), [noexcept operator](https://en.cppreference.com/w/cpp/language/noexcept), [Dynamic exception specification](https://en.cppreference.com/w/cpp/language/except_spec), [std::move_if_noexcept](https://en.cppreference.com/w/cpp/utility/move_if_noexcept), [std::terminate](https://en.cppreference.com/w/cpp/error/terminate)
- **Prerequisites:** exceptions-and-stack-unwinding, copy-and-move

## The one idea

`noexcept` is not a compile-time check. Marking a function `noexcept` does not make the compiler prove that nothing inside it throws. It changes what happens when something does: instead of propagating, the exception reaches the function boundary and `std::terminate` is called.

What makes the promise valuable is that other code can **ask about it at compile time**. The `noexcept` operator turns "can this expression throw?" into a `bool` constant, and the standard library uses that answer to choose faster algorithms, most famously moving rather than copying when a `std::vector` grows.

> **Mental model.** `noexcept` is a contract written in the type system and enforced by termination. Callers read it statically; the runtime enforces it only by ending the program.

## The specifier and the operator

The specifier comes in three spellings. `noexcept` and `noexcept(true)` mean the function has a **non-throwing** exception specification. `noexcept(false)`, or no specifier at all for most functions, means it is **potentially throwing**. The argument must be a contextually converted constant expression of type `bool`, so it may depend on template parameters.

The operator, `noexcept(expr)`, is an unevaluated operand like `sizeof`. It yields `false` if the expression is potentially throwing: if it calls any function, constructor, conversion or destructor that is potentially throwing, or contains a `throw`, a `dynamic_cast` to a reference type that needs a run-time check, or a `typeid` applied to a dereferenced polymorphic glvalue. It yields `true` otherwise. Nothing in the operand runs.

```cpp
int calls = 0;
int count() { return ++calls; }

static_assert(!noexcept(count()));  // count is potentially throwing
static_assert(noexcept(1 + 2));     // no call, cannot throw
static_assert(!noexcept(new int));  // operator new may throw bad_alloc

struct Leaky { ~Leaky() noexcept(false); };
static_assert(!noexcept(Leaky()));  // the temporary's destructor counts
// calls is still 0: the operand was never evaluated
```

The two are combined in the **conditional noexcept** idiom, where the doubled keyword is not a typo. The outer `noexcept` is the specifier, and the inner one is the operator computing its argument.

```cpp
#include <type_traits>
#include <utility>

template <class T>
struct Box {
  T value;
  Box(Box&& other) noexcept(noexcept(T(std::move(other.value))))
      : value(std::move(other.value)) {}

  void swap(Box& o) noexcept(std::is_nothrow_swappable_v<T>) {
    using std::swap;
    swap(value, o.value);
  }
};
```

Traits such as `std::is_nothrow_move_constructible_v` and `std::is_nothrow_invocable_v` are usually clearer than spelling out the expression, and they are implemented with the operator.

## What happens when a noexcept function throws

If an exception tries to leave a function with a non-throwing specification, `std::terminate` is called. The exception is not propagated, and no handler outside the function ever sees it. Handlers inside the function work normally; the boundary only matters for exceptions that would cross it.

> **Standardese.** [except.terminate] makes it implementation-defined whether the stack is unwound, unwound partially, or not unwound at all before `std::terminate` is called in this case. That latitude is what lets compilers omit unwind tables for `noexcept` functions.

The partial case is real. With GCC 16 and Clang 21, the inner frame's locals are destroyed while searching upward, but the `noexcept` frame's own locals are not, because the search stops at its boundary.

```cpp
#include <cstdio>
#include <stdexcept>

struct Note { const char* n; ~Note() { std::fprintf(stderr, "~%s\n", n); } };

void inner() { Note a{"inner"}; throw std::runtime_error("x"); }
void outer() noexcept { Note b{"outer"}; inner(); }

int main() {
  try { outer(); } catch (...) { std::puts("never reached"); }
}
// std::terminate. GCC and Clang print ~inner but not ~outer;
// another implementation could print both or neither.
```

Compilers warn when they can see a `throw` that will always reach a `noexcept` boundary, but the rule is not enforced at compile time, and a call to a potentially-throwing function from a `noexcept` function is always well-formed.

## Implicit noexcept

You get non-throwing specifications without writing them in several places.

- **Destructors.** A destructor declared without a specifier, whether user-written or implicit, has the specification its implicit version would have, which is non-throwing unless some base or member has a potentially-throwing destructor. A deallocation function without a specifier is non-throwing as well.
- **Implicitly declared and defaulted special members.** A default constructor, copy or move constructor, copy or move assignment, or comparison that is implicitly declared or defaulted on its first declaration is non-throwing exactly when every function it would call is non-throwing.
- **Explicitly defaulted with a different specifier.** Since C++20, writing `S(S&&) noexcept(false) = default;` is allowed and the written specification wins. Before C++20, a mismatch on a first declaration made the function deleted.

```cpp
#include <string>
#include <type_traits>

struct Plain { std::string s; };
static_assert(std::is_nothrow_move_constructible_v<Plain>);    // string's move is noexcept
static_assert(!std::is_nothrow_copy_constructible_v<Plain>);   // copying may allocate
static_assert(std::is_nothrow_destructible_v<Plain>);

struct Throws { ~Throws() noexcept(false); };
struct Holds { Throws t; };
static_assert(!std::is_nothrow_destructible_v<Holds>);         // inherited from the member
```

> **Pitfall.** A destructor you write yourself is still implicitly `noexcept`. A `throw` in it, even one meant to report a failed flush, calls `std::terminate` unless you write `noexcept(false)`, and even then it terminates if the destructor runs during unwinding.

## Why move constructors should be noexcept

When `std::vector` reallocates, it must relocate existing elements to the new buffer while keeping the strong guarantee for `push_back`: if something throws, the original vector is untouched. Moving elements destroys that option, because a move that throws halfway leaves some elements moved-from in the old buffer. So the library uses `std::move_if_noexcept`, which moves only when the move constructor is non-throwing or the type cannot be copied, and copies otherwise.

```cpp
#include <cstdio>
#include <vector>

struct Slow {
  Slow() = default;
  Slow(const Slow&) { std::puts("copy"); }
  Slow(Slow&&) { std::puts("move"); }           // potentially throwing
};
struct Fast {
  Fast() = default;
  Fast(const Fast&) { std::puts("copy"); }
  Fast(Fast&&) noexcept { std::puts("move"); }
};

int main() {
  std::vector<Slow> a(1); a.reserve(2);         // prints copy
  std::vector<Fast> b(1); b.reserve(2);         // prints move
}
```

A move constructor that cannot actually throw, but is not declared `noexcept`, silently turns every reallocation into a deep copy. A defaulted move constructor gets this right automatically when all members have non-throwing moves; a hand-written one needs the keyword.

## noexcept in the type system

Since C++17, the exception specification is part of the function type: `void() noexcept` and `void()` are distinct types, as are pointers to them. A **function pointer conversion** goes one way only: a pointer to a `noexcept` function converts to a pointer to the potentially-throwing type, never the reverse.

```cpp
void safe() noexcept;
void risky();

void (*p)() = safe;               // OK: drops the promise
// void (*q)() noexcept = risky;  // ill-formed: would invent a promise

struct S { void m() noexcept; };
void (S::*pm)() = &S::m;          // OK: same rule for member pointers

template <bool B> constexpr bool is_nothrow(void (*)() noexcept(B)) { return B; }
static_assert(is_nothrow(safe) && !is_nothrow(risky));  // B is deducible
```

You still cannot overload on the specification: declaring `void f();` and `void f() noexcept;` is an ill-formed redeclaration, not an overload. Every declaration of a function must agree on its specification, apart from the implicit cases above.

Virtual functions follow the same direction. If a virtual function is non-throwing, every overrider must be non-throwing too, since callers through the base have been promised it. An overrider may add `noexcept` to a potentially-throwing base function.

Lambdas take the specifier after the parameter list, and a captureless `noexcept` lambda converts to a `noexcept` function pointer.

## The road from throw() to noexcept

C++98 had **dynamic exception specifications**, `throw(A, B)`, which listed permitted exception types and called `std::unexpected` at run time if another escaped. They cost run-time checks, did not compose with templates, and nobody could write them correctly for generic code. C++11 deprecated them and added `noexcept`. C++17 removed `throw(A, B)` and `std::unexpected`, and kept `throw()` only as a deprecated synonym for `noexcept(true)`. C++20 removed `throw()` as well, although GCC 16 and Clang 21 still accept it in C++20 and C++23 modes as an extension.

The standard library is deliberately sparing with `noexcept`. Functions with preconditions, such as `std::vector::operator[]`, are not specified `noexcept`, so that a checking implementation could report a violation by throwing. Implementations may add `noexcept` to non-virtual library functions, and libstdc++ and libc++ both mark `operator[]` that way, so `noexcept(v[0])` is `true` in practice and not guaranteed by the standard.

### When to write it

The promise is easy to add and hard to take back. Once callers have written `static_assert(noexcept(f()))`, or chosen an algorithm because a trait said "nothrow", removing the keyword is a breaking change, even if the function's behaviour on success is unchanged. That argues for writing `noexcept` deliberately, in a few places where it pays for itself.

- **Move constructors and move assignment** of types that own resources, because containers and algorithms branch on them.
- **`swap`**, because copy-and-swap and many algorithms are only safe when it cannot fail.
- **Destructors and deallocation** are already non-throwing by default; leave them that way.
- **Hash functions and simple accessors** that genuinely cannot fail, where the promise documents a fact rather than a hope.

Everywhere else, the default of potentially throwing is the honest one. A function that allocates, calls user callbacks, or has preconditions that a future version might want to check by throwing should stay without the keyword, following the same reasoning the library applies to itself. In generic code, prefer a conditional specification computed from the operations you call, so that the promise is exactly as strong as your element types allow and no stronger.

## What to remember

- `noexcept` promises, it does not prove; an escaping exception calls `std::terminate`.
- Whether the stack unwinds before that termination is implementation-defined, and may be partial.
- The `noexcept` operator is unevaluated and asks whether an expression is potentially throwing, including temporaries' destructors and `new`.
- `noexcept(noexcept(expr))` is the conditional idiom; prefer `is_nothrow_*` traits when they fit.
- Destructors and implicit or defaulted special members are `noexcept` whenever what they call is.
- Since C++17 `noexcept` is part of the function type; pointers may drop it but not gain it, and overriders of a `noexcept` virtual must keep it.
- Non-`noexcept` move constructors make `std::vector` copy on reallocation.
- Dynamic exception specifications are gone: `throw(T)` in C++17, `throw()` in C++20.

## Concept Map Outline

- **noexcept:** A no-throw promise in the type system, read at compile time and enforced by std::terminate.
  - **Specifier:** noexcept or noexcept(true) is non-throwing; noexcept(false) or nothing is potentially throwing.
    - **Constant bool argument:** The argument is a constant expression and may depend on template parameters.
    - **Conditional idiom:** noexcept(noexcept(expr)): the outer is the specifier, the inner is the operator.
    - **Not checked statically:** Calling throwing code from a noexcept function is well-formed; compilers only warn.
  - **Operator:** noexcept(expr) is an unevaluated bool constant: false if expr is potentially throwing.
    - **Unevaluated:** Like sizeof, the operand never runs, so side effects never happen.
    - **Hidden calls count:** Temporaries' destructors, conversions and operator new all make the result false.
    - **Traits:** is_nothrow_move_constructible and friends are built on the operator.
  - **Violation:** An exception reaching a noexcept boundary calls std::terminate.
    - **Unwinding unspecified:** Implementation-defined whether the stack is unwound fully, partially or not at all.
    - **Inner handlers work:** Only exceptions that would cross the noexcept boundary terminate.
  - **Implicit noexcept:** Some functions get a non-throwing specification without the keyword.
    - **Destructors:** Non-throwing unless a base or member destructor is potentially throwing.
    - **Defaulted specials:** Non-throwing exactly when every function they would call is non-throwing.
    - **C++20 explicit default:** A written specifier on a defaulted function now wins; before, a mismatch deleted it.
  - **Type system (C++17):** The exception specification is part of the function type.
    - **One-way conversion:** Pointers to noexcept functions convert to plain pointers, never the reverse.
    - **No overloading:** f() and f() noexcept conflict as redeclarations; they cannot overload.
    - **Virtual overrides:** An overrider of a noexcept virtual must be noexcept; adding noexcept is fine.
    - **Deducible:** Templates can deduce B from void(*)() noexcept(B).
  - **Why it matters:** Libraries choose algorithms based on the answer.
    - **move_if_noexcept:** vector reallocation copies copyable elements whose move may throw.
    - **Dynamic specs removed:** throw(T) removed in C++17, throw() removed in C++20.
    - **Narrow contracts:** The standard leaves functions with preconditions potentially throwing; vendors may add noexcept.

## Standardese Quiz Questions

### Question 1 [warmup] ([expr.unary.noexcept], [except.spec])

What does this program print?

```cpp
#include <cstdio>

int main() {
  int n = 0;
  bool b = noexcept(n++);
  std::printf("%d %d\n", n, b);
}
```

A. `1 1`
B. `0 0`
C. `1 0`
D. `0 1`

**Answer (D):** `0 1`

**Why:** The operand of the `noexcept` operator is unevaluated, exactly like the operand of `sizeof`, so `n++` never runs and `n` stays 0. A built-in increment calls no function and cannot throw, so the result is `true`, printed as 1. The tempting `1 1` assumes the operand is executed to find out whether it throws.

### Question 2 [warmup] ([conv.fctptr], [except.spec], [dcl.fct])

In C++23, which initialization is ill-formed?

```cpp
void safe() noexcept;
void risky();

void (*a)() = safe;           // #1
void (*b)() noexcept = safe;  // #2
void (*c)() noexcept = risky; // #3
auto d = +[]() noexcept {};   // #4
```

A. #1, because the types differ in their exception specification
B. #3
C. #4, because a lambda's exception specification is not part of its conversion
D. None of them; the exception specification is not part of the type

**Answer (B):** #3

**Why:** Since C++17 `noexcept` is part of the function type, and the function pointer conversion only removes it: a pointer to a non-throwing function converts to a pointer to a potentially-throwing one, which makes #1 fine. #3 would add a promise that `risky` never made, so it is ill-formed. The last option describes C++14, where the specification was not part of the type.

### Question 3 [warmup] ([vector.capacity], [except.spec])

What does this program print?

```cpp
#include <cstdio>
#include <vector>

struct Slow {
  Slow() = default;
  Slow(const Slow&) { std::puts("copy"); }
  Slow(Slow&&) { std::puts("move"); }
};

int main() {
  std::vector<Slow> v(1);
  v.reserve(10);
}
```

A. `copy`
B. `move`
C. Nothing; `reserve` does not touch existing elements
D. Either `copy` or `move`; it is unspecified

**Answer (A):** `copy`

**Why:** `reserve` beyond the current capacity reallocates and must relocate the existing element while keeping the strong guarantee. Because `Slow`'s move constructor is potentially throwing and `Slow` is copyable, the library uses `std::move_if_noexcept`, which yields an lvalue and selects the copy constructor. Marking the move constructor `noexcept` would make it print `move`.

### Question 4 [tricky] ([class.dtor], [except.spec], [except.terminate])

What happens when this program runs?

```cpp
#include <cstdio>

struct Closer {
  ~Closer() { throw 1; }
};

int main() {
  try {
    Closer c;
  } catch (int) {
    std::puts("caught");
  }
}
```

A. Prints `caught`, since no other exception is in flight
B. Ill-formed: a destructor cannot contain a `throw`
C. `std::terminate` is called
D. Undefined behavior

**Answer (C):** `std::terminate` is called

**Why:** A destructor declared without a specifier gets the specification of the implicit destructor, which is non-throwing here because `Closer` has no members or bases with throwing destructors. The exception therefore hits a `noexcept` boundary and `std::terminate` is called. `caught` would only be printed if the destructor were declared `noexcept(false)`; the code is well-formed, and compilers merely warn.

### Question 5 [tricky] ([except.spec], [class.virtual])

Which statement about this code is true?

```cpp
struct Base {
  virtual void a() noexcept;
  virtual void b();
};

struct Derived : Base {
  void a() override;           // #1
  void b() noexcept override;  // #2
};
```

A. Both overrides are well-formed; exception specifications do not affect overriding
B. #1 is well-formed and #2 is ill-formed
C. Both are ill-formed; an overrider must have exactly the same specification
D. #1 is ill-formed and #2 is well-formed

**Answer (D):** #1 is ill-formed and #2 is well-formed

**Why:** Code calling `a()` through a `Base&` has been promised it will not throw, so an overrider of a non-throwing virtual function must itself be non-throwing, and #1 is ill-formed. The reverse is fine: `Derived::b` makes a stronger promise than `Base::b`, which callers through the base can only benefit from. Requiring an exact match, as the third option claims, is stricter than the rule.

### Question 6 [tricky] ([expr.unary.noexcept], [except.spec], [class.temporary])

What is the value of `r`?

```cpp
struct Leaky {
  ~Leaky() noexcept(false);
};

Leaky make() noexcept;

constexpr bool r = noexcept(make());
```

A. `true`, because `make` is `noexcept`
B. `false`
C. Ill-formed: `make` is declared but not defined
D. Ill-formed: the operand of `noexcept` must not create a temporary

**Answer (B):** `false`

**Why:** The operand `make()` is a prvalue that is a full-expression, so a temporary is materialized and destroyed at its end, and that destruction is part of the expression the operator inspects. `~Leaky` is potentially throwing, so the whole expression is potentially throwing and the result is `false`. Looking only at the called function, as the first option does, misses the implicit destructor call. Because the operand is unevaluated, no definition of `make` is needed.

### Question 7 [standardese] ([except.terminate], [except.spec])

An exception thrown in `g` propagates up to `f`, which is declared `noexcept`, with no handler in between. What does the C++23 standard say?

A. The exception propagates to `f`'s caller, because `noexcept` is only an optimization hint
B. `std::terminate` is called after all locals in `g` and `f` have been destroyed
C. `std::terminate` is called; whether the stack is unwound, partially unwound or not unwound first is implementation-defined
D. The behavior is undefined

**Answer (C):** `std::terminate` is called; whether the stack is unwound, partially unwound or not unwound first is implementation-defined

**Why:** [except.terminate] says that when the search for a handler reaches the outermost block of a function with a non-throwing exception specification, `std::terminate` is called, and it is implementation-defined whether the stack is unwound, unwound partially, or not unwound at all. GCC and Clang destroy `g`'s locals but not `f`'s. The second option is tempting because full unwinding is what happens when a handler is found, but no handler is found here. The behavior is defined, just not fully specified.

### Question 8 [standardese] ([except.spec], [diff.cpp14.except])

Compiled as C++17, is this declaration well-formed?

```cpp
void parse() throw(int);
```

A. Ill-formed: dynamic exception specifications with types were removed in C++17
B. Well-formed but deprecated, as in C++11 and C++14
C. Well-formed, and equivalent to `noexcept(false)`
D. Well-formed, and calls `std::unexpected` if anything other than an `int` escapes

**Answer (A):** Ill-formed: dynamic exception specifications with types were removed in C++17

**Why:** C++11 deprecated dynamic exception specifications, and C++17 removed every form except the empty `throw()`, which it kept as a deprecated synonym for `noexcept(true)` until C++20 removed it too. `std::unexpected`, the handler the last option describes, was removed in C++17 along with them. The second option is the C++14 answer.
