← C++ Index

⚠️ <stdexcept> — Standard Exception Classes

The standard hierarchy of exception classes, all derived from std::exception. Always catch by const reference.

Include: #include <stdexcept> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::exceptionbase classRoot of all standard exceptions; has what()
std::runtime_error: exceptionError detected at runtime
std::logic_error: exceptionLogic bug in the program
std::invalid_argument: logic_errorInvalid argument passed to a function
std::out_of_range: logic_errorAccess beyond valid range
std::overflow_error:runtime_errorArithmetic overflow
std::bad_alloc: exceptionThrown by new when allocation fails
std::bad_cast: exceptionThrown by dynamic_cast on invalid cast
e.what()const char *Return description of the exception
throw exprstatementThrow an exception object
try { } catch(T &e) {}statementCatch block — use const reference
catch(...) {}statementCatch any exception (use as last resort)

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;

double safe_divide(double a, double b) {
    if (b == 0.0) throw invalid_argument("Division by zero");
    return a / b;
}

int main() {
    try {
        cout << safe_divide(10.0, 2.0) << "\n";
        cout << safe_divide(10.0, 0.0) << "\n"; // throws
    }
    catch (const invalid_argument &e) {
        cerr << "Invalid argument: " << e.what() << "\n";
    }

    try {
        vector<int> v = {1, 2, 3};
        cout << v.at(10) << "\n";  // throws out_of_range
    }
    catch (const out_of_range &e) {
        cerr << "Out of range: " << e.what() << "\n";
    }

    try { throw runtime_error("Something went wrong"); }
    catch (const exception &e) {
        cerr << "Caught: " << e.what() << "\n";
    }

    cout << "Program continues after exceptions.\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -o except_demo except_demo.cpp

← <memory>  |  🏠 Index  |  <thread> →