example4_standard_exceptions.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <exception>
#include <stdexcept>
#include <iostream>
#include <vector>

void demonstrateExceptions() {
    std::vector<int> vec(5);

    try {
        // Demonstrate out_of_range
        std::cout << vec.at(10) << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range error: " << e.what() << std::endl;
    }

    try {
        // Demonstrate bad_alloc
        std::vector<int> tempVec;
        std::vector<int> hugeVector(tempVec.max_size());
    } catch (const std::bad_alloc& e) {
        std::cerr << "Bad allocation error: " << e.what() << std::endl;
    }

    try {
        // Demonstrate invalid_argument
        std::stoi("not a number");
    } catch (const std::invalid_argument& e) {
        std::cerr << "Invalid argument error: " << e.what() << std::endl;
    }
}

int main() {
    try {
        demonstrateExceptions();
    } catch (const std::exception& e) {
        std::cerr << "Caught unhandled exception: " << e.what() << std::endl;
    }

    return 0;
}
Back to exception