Noexcept Specifier in C++

Level 5542 keystrokes

noexcept marks a function that promises not to throw. The noexcept(...) operator checks at compile time, without running the call, whether an expression is declared not to throw: 1 for safeSwap and 0 for mayThrow.

C++ code

// noexcept: promises not to throw (if it did, std::terminate would be called)
1void safeSwap(int& a, int& b) noexcept {
// Swaps the two values through a temporary
2 int temp = a;
3 a = b;
4 b = temp;
5}
6
// No noexcept: this function may throw
7void mayThrow(int x) {
// Throws for negative values
8 if (x < 0) throw runtime_error("negative value");
9 cout << "Value: " << x << endl;
10}
11
// Helper that would report noexcept for any callable (not called below)
12template<typename F>
13void checkNoexcept(F func, const char* name) {
// noexcept(expr) is a compile-time check; func() is not actually called
14 cout << name << " is noexcept: " << noexcept(func()) << endl;
15}
16
17int x = 5, y = 10;
// Swaps x and y
18safeSwap(x, y);
// Prints "After swap: x=10, y=5"
19cout << "After swap: x=" << x << ", y=" << y << endl;
20
// Declared noexcept: 1 (the swap inside is not executed)
21cout << "safeSwap is noexcept: " << noexcept(safeSwap(x, y)) << endl;
// Not noexcept: 0
22cout << "mayThrow is noexcept: " << noexcept(mayThrow(1)) << endl;

Output

After swap: x=10, y=5
safeSwap is noexcept: 1
mayThrow is noexcept: 0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 38
  • "× 14
  • (× 12
  • )× 12
  • ;× 11
  • =× 7
  • ,× 6
  • :× 5
  • {× 3
  • }× 3

More C++ examples at level 5

← C++ typing practice