Exception Specification

Exception Specifications and noexcept in C++

IntermediateTopic: Exception Handling Programs
Back

C++ Exception Specification Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <stdexcept>
using namespace std;

// Function that may throw exceptions
int divide(int a, int b) {
    if (b == 0) {
        throw runtime_error("Division by zero");
    }
    return a / b;
}

// Function that doesn't throw (noexcept)
int add(int a, int b) noexcept {
    return a + b;
}

// Function with exception specification (deprecated in C++11)
void mayThrow() throw(runtime_error) {
    throw runtime_error("This function may throw");
}

int main() {
    // noexcept function - safe to call
    cout << "Add (noexcept): " << add(5, 3) << endl;
    
    // Function that may throw - use try-catch
    try {
        cout << "Divide: " << divide(10, 2) << endl;
        cout << "Divide by zero: " << divide(10, 0) << endl;
    } catch (const runtime_error& e) {
        cout << "Caught: " << e.what() << endl;
    }
    
    // noexcept operator - check if function is noexcept
    cout << "\nadd() is noexcept: " << noexcept(add(1, 2)) << endl;
    cout << "divide() is noexcept: " << noexcept(divide(1, 2)) << endl;
    
    return 0;
}
Output
Add (noexcept): 8
Divide: 5
Caught: Division by zero

add() is noexcept: 1
divide() is noexcept: 0

Understanding Exception Specification

This program teaches you about Exception Specifications and noexcept in C++. The noexcept specifier indicates that a function will not throw exceptions, enabling compiler optimizations and providing guarantees about exception safety.

---

1. What This Program Does

The program demonstrates exception specifications:

Using noexcept specifier
Functions that don't throw exceptions
Checking if function is noexcept
Exception specifications (deprecated)

Exception specifications enable exception safety guarantees.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <stdexcept>
Provides standard exception classes.

---

3. 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

---

4. noexcept Functions

Declaration

:

int add(int a, int b) noexcept {

}

    return a + b;

How it works

:

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

---

5. Functions That May Throw

Without noexcept

:

int divide(int a, int b) {

if (b == 0) {

throw runtime_error("Division by zero");

}

}

    return a / b;

How it works

:

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

---

6. noexcept Operator

Checking noexcept

:

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

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

How it works

:

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

---

7. Exception Specifications (Deprecated)

Old Syntax

:

void mayThrow() throw(runtime_error) {

throw runtime_error("Error");

}

How it works

:

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

---

8. When to Use noexcept

Best For

:

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

---

9. 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

---

10. return 0;

This ends the program successfully.

---

Summary

noexcept: specifies function won't throw exceptions, enables compiler optimizations.
noexcept operator: checks if function/expression is noexcept at compile-time.
Exception specifications (throw(...)): deprecated in C++11, use noexcept instead.
Mark functions noexcept when they guarantee no exceptions.
Understanding noexcept enables exception safety guarantees and optimizations.
Essential for performance-critical code and clear exception contracts.

This program is fundamental for learning exception specifications, understanding noexcept, and preparing for exception-safe and optimized code in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Exception Specification

This C++ program is part of the "Exception Handling Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents