Exception Specification
Exception Specifications and noexcept in C++
C++ Exception Specification Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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;
}Add (noexcept): 8 Divide: 5 Caught: Division by zero add() is noexcept: 1 divide() is noexcept: 0
Understanding Exception Specification
noexcept specifies that a function will not throw exceptions. noexcept functions are optimized by compiler. Use noexcept operator to check if function is noexcept. Exception specifications (throw(...)) are deprecated in C++11. noexcept(true) means no exceptions, noexcept(false) means may throw. Mark functions noexcept when they guarantee no exceptions.
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.