Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Exception Specification in C++

Learn noexcept in C++: mark functions that never throw, test expressions with the noexcept operator, and see why throw(type) specifications were removed in C++17.

IntermediateException Handling ProgramsExample 4 of 5
exception-specification.cpp
1#include <iostream>
2#include <stdexcept>
3using namespace std;
4
5// Function that may throw exceptions
6int divide(int a, int b) {
7 if (b == 0) {
8 throw runtime_error("Division by zero");
9 }
10 return a / b;
11}
12
13// Function that doesn't throw (noexcept)
14int add(int a, int b) noexcept {
15 return a + b;
16}
17
18// Old style was: void mayThrow() throw(runtime_error)
19// Dynamic exception specifications were deprecated in C++11 and removed in C++17
20void mayThrow() noexcept(false) {
21 throw runtime_error("This function may throw");
22}
23
24int main() {
25 // noexcept function - safe to call
26 cout << "Add (noexcept): " << add(5, 3) << endl;
27
28 // Function that may throw - use try-catch
29 try {
30 cout << "Divide: " << divide(10, 2) << endl;
31 cout << "Divide by zero: " << divide(10, 0) << endl;
32 } catch (const runtime_error& e) {
33 cout << "Caught: " << e.what() << endl;
34 }
35
36 // noexcept operator - check if function is noexcept
37 cout << "\nadd() is noexcept: " << noexcept(add(1, 2)) << endl;
38 cout << "divide() is noexcept: " << noexcept(divide(1, 2)) << endl;
39
40 return 0;
41}

Sample Output

Divide by zero: Caught: Division by zero

The label printed before the throw; the catch finished the line.

add() is noexcept: 1

true prints as 1.

In this one

  • What the noexcept specifier promises
  • What happens if a noexcept function throws
  • How the noexcept operator differs from the specifier
  • Why throw(type) no longer compiles

How it works

  1. 1

    add(5, 3) is noexcept and prints 8.

  2. 2

    divide(10, 2) prints 5.

  3. 3

    divide(10, 0) throws after "Divide by zero: " was printed; the catch finishes the line.

  4. 4

    noexcept(add(1,2)) prints 1; noexcept(divide(1,2)) prints 0.

Edge cases

Throwing from a noexcept function

Add throw 1; inside add.

The program calls std::terminate. A surrounding try-catch does not help.

Old syntax

Write void f() throw(runtime_error) and compile with -std=c++17.

The compiler rejects it because dynamic exception specifications were removed. throw() with empty parentheses also went away in C++20.

What's going on

An exception specification is part of a function's declaration that says whether it can throw. Modern C++ has one form that matters, noexcept.

int add(int a, int b) noexcept promises that add never throws. The compiler can optimize around that, and the standard library relies on it: for example, vector only moves elements during growth if the move constructor is noexcept, and copies them otherwise. If a noexcept function does throw, the program calls std::terminate right away; the exception cannot be caught outside.

divide has no specification, so it may throw. Called with 10 and 2 it prints 5. Called with 10 and 0 it throws runtime_error, which the catch prints.

Look at the output line "Divide by zero: Caught: Division by zero". Since C++17, the parts of a << chain run left to right, so "Divide by zero: " is printed before divide(10, 0) is even called. Then the throw skips the rest of the line, and the catch prints on the same line because no newline was written yet. Splitting that statement into two lines, or computing the result before printing, avoids the half-printed line.

noexcept(add(1, 2)) is the noexcept operator, which is different from the specifier. It does not call anything; it asks at compile time whether the expression is declared not to throw, and gives true or false. cout prints those as 1 and 0.

mayThrow shows the history. The original version of this program declared it as void mayThrow() throw(runtime_error), a dynamic exception specification that listed allowed exception types. That form was deprecated in C++11 and removed in C++17, so it no longer compiles with a modern compiler at its default settings. The code now says noexcept(false), which means "may throw", the same as writing nothing. The function is never called in main; it is only there to show the syntax.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <stdexcept> is there because it provides standard exception classes. Leave one out and the compiler stops at the first name it does not recognize.

Understanding noexcept

noexcept Concept:

Specifies function won't throw
Compiler optimization hint
Exception safety guarantee
Modern C++11+ approach

Benefits:

Compiler optimizations
Clear exception contracts
Better performance
Exception safety guarantees

noexcept Functions

Declaration:

int add(int a, int b) noexcept {

return a + b;

}

What happens here:

noexcept: function won't throw
Compiler can optimize
If exception thrown, terminate()
Safety guarantee

Functions That May Throw

Without noexcept:

int divide(int a, int b) {

if (b == 0) {

throw runtime_error("Division by zero");

}

return a / b;

}

What happens here:

No noexcept: may throw
Must use try-catch
Handle exceptions
No optimization guarantee

noexcept Operator

Checking noexcept:

noexcept(add(1, 2)) // Returns true

noexcept(divide(1, 2)) // Returns false

What happens here:

Checks if expression is noexcept
Returns true/false
Compile-time check
Useful for templates

Exception Specifications (Deprecated)

Old Syntax:

void mayThrow() throw(runtime_error) {

throw runtime_error("Error");

}

What happens here:

Deprecated in C++11
Old exception specification
Use noexcept instead
Not recommended

When to Use noexcept

Good fits:

Functions that never throw
Performance-critical code
Move constructors/assignments
Destructors (usually)
Simple utility functions

Example Scenarios:

Simple arithmetic
Getters/setters
Move operations
Destructors
Utility functions

Important Considerations

Exception Safety:

noexcept = guarantee no throw
If exception thrown, terminate()
Be certain before using
Test thoroughly

Performance:

Compiler optimizations
Better code generation
Reduced overhead
Faster execution

Contracts:

Clear exception contracts
Document behavior
Help with debugging
Better code understanding

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does noexcept(divide(1, 2)) evaluate to?

Pick an answer to check it.

Question 2

What happens if a noexcept function throws?

Pick an answer to check it.

Questions people ask

When should I mark a function noexcept?

Move constructors, move assignment, swap, and destructors should almost always be noexcept. Elsewhere, only when you are sure.

Are destructors noexcept by default?

Yes, unless a member's destructor can throw.

Does noexcept make code faster?

Sometimes a little, and it lets containers choose moves over copies.