example3_nested_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
#include <exception>
#include <stdexcept>
#include <iostream>

void innerFunction() {
    throw std::runtime_error("Inner error");
}

void outerFunction() {
    try {
        innerFunction();
    } catch (const std::exception& e) {
        std::throw_with_nested(std::runtime_error("Outer error"));
    }
}

void printException(const std::exception& e, int level = 0) {
    std::cerr << std::string(level, ' ') << "Exception: " << e.what() << std::endl;
    try {
        std::rethrow_if_nested(e);
    } catch (const std::exception& nested) {
        printException(nested, level + 1);
    }
}

int main() {
    try {
        outerFunction();
    } catch (const std::exception& e) {
        std::cout << "Caught exception. Hierarchy:" << std::endl;
        printException(e);
    }

    return 0;
}
Back to exception