Standard Exceptions & Custom Exception Classes

🟡 Intermediate

📖 Definition

The <stdexcept> header defines standard exception classes inheriting from std::exception (e.g. std::runtime_error, std::invalid_argument, std::out_of_range) providing a .what() virtual method to retrieve descriptive error messages.

💡 Code Example

#include <iostream>
#include <stdexcept>

void validateAge(int age) {
    if (age < 0) throw std::invalid_argument("Age cannot be negative!");
}

int main() {
    try {
        validateAge(-5);
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << "\n";
    }
    return 0;
}