example2_strong_exception_safety.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
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>

class Database {
private:
    std::vector<int> data;

public:
    void addBatch(const std::vector<int>& newData) {
        auto oldSize = data.size();
        try {
            data.insert(data.end(), newData.begin(), newData.end());
        } catch (...) {
            // Rollback on any exception
            data.resize(oldSize);
            throw; // Re-throw the caught exception
        }
    }

    void display() const {
        for (const auto& item : data) {
            std::cout << item << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    Database db;
    std::vector<int> batch1 = {1, 2, 3};
    std::vector<int> batch2 = {4, 5, 6};

    try {
        db.addBatch(batch1);
        db.addBatch(batch2);
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    db.display();
    return 0;
}
Back to exception_safety