noexcept
- C++ course
- Advanced
- Lesson 77/83
- 5 min
Learn exception specification with noexcept.
What is noexcept?
noexcept is a specifier that states a function will not throw. It gives a safety contract to the compiler and to the reader. If it does throw, std::terminate is called.
Example: void swap_ints(int& a, int& b) noexcept { int t = a; a = b; b = t; }. This function does simple assignments and cannot throw. Thanks to noexcept the compiler produces better code and callers can use it freely. Destructors, swap and move operations should be noexcept. This is also critical for optimal behaviour in move semantics.
noexcept function pointer
noexcept is part of the function type. A noexcept function pointer only accepts noexcept functions.
Example: void (*p)(int) noexcept = &some_func;. Here some_func must also be noexcept. This makes callback interfaces safe: the caller knows the callback will not throw. In modern C++, marking noexcept acts as both documentation and contract. The standard library uses noexcept information to pick the best behaviour for move operations.
Practice Write a noexcept swap_ints
Write void swap_ints(int& a, int& b) noexcept with body int t = a; a = b; b = t;. In main define int x = 3, y = 7;, call swap_ints(x, y) and print with std::cout << x << y;.
Starter code
#include <iostream>
// Write the swap_ints function with noexcept
int main() {
// Define x and y, call it and print
return 0;
}Sample solution
#include <iostream>
void swap_ints(int& a, int& b) noexcept {
int t = a;
a = b;
b = t;
}
int main() {
int x = 3, y = 7;
swap_ints(x, y);
std::cout << x << y;
return 0;
}Expected output
73
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the noexcept usage
| Term | Meaning |
|---|---|
destructor |
should be noexcept |
swap |
nothrow swap |
move constructor |
noexcept move |
std::terminate |
called on violation |
2 What happens if a noexcept function throws?
- std::terminate is called Correct answer
- The exception is ignored
- The program continues
- A compile error is given
Explanation: If a noexcept function throws, std::terminate is called and the program ends.
3 the noexcept keyword
void swap_ints(int& a, int& b) ____ { int t = a; a = b; b = t; }
void swap_ints(int& a, int& b) noexcept { int t = a; a = b; b = t; }
Explanation: noexcept states the function will not throw.