example1_strong_exception_guaranty.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
41
42
43
44
45
#include <iostream>
#include <vector>
#include <stdexcept>

class Resource {
public:
    Resource(int id) : id_(id) {
        std::cout << "Resource " << id_ << " acquired\n";
    }
    ~Resource() {
        std::cout << "Resource " << id_ << " released\n";
    }
private:
    int id_;
};

class StrongExceptionGuarantee {
public:
    void operation(int n) {
        std::vector<Resource> resources;
        for (int i = 0; i < n; ++i) {
            resources.push_back(Resource(i));
            if (i == 2) {
                throw std::runtime_error("Simulated error");
				// Exception thrown here
            	// Stack unwinding begins:
            	// 1. vector's destructor is called
            	// 2. vector's destructor calls Resource destructor for each element
            	// 3. Each Resource prints its "released" message
            	// 4. vector is fully destroyed
            	// 5. Exception continues propagating
            }
        }
    }
};

int main() {
    StrongExceptionGuarantee seg;
    try {
        seg.operation(5);
    } catch (const std::exception& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
Back to exceptions