Site Tools


wiki:hpp-stdexcept

Table of Contents

<stdexcept>

<stdexcept> defines standard exception classes: std::logic_error (programming error), std::runtime_error (runtime failure), and their subclasses (std::invalid_argument, std::out_of_range, std::overflow_error, etc.).

Derive your own exceptions from these when you need domain-specific errors.

Example

This example throws and catches an invalid_argument exception when validating a negative value.

// compile: g++ -std=c++11 -o stdexceptexample stdexceptexample.cpp
// run: ./stdexceptexample
// description: throw and catch standard exceptions
 
#include <stdexcept>
#include <iostream>
 
void validate(int value) {
    if (value < 0) {
        throw std::invalid_argument("value must be non-negative");
    }
}
 
int main() {
    try {
        validate(-5);
    } catch (const std::invalid_argument& e) {
        std::cout << "caught: " << e.what() << "\n";
    }
 
    return 0;
}
wiki/hpp-stdexcept.md · Last modified: by 127.0.0.1