example1_basic_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
#include <iostream>
#include <stdexcept>
#include <vector>

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

public:
    void addData(int value) noexcept {
        try {
            data.push_back(value);
        } catch (const std::bad_alloc&) {
            // Handle allocation failure
            std::cerr << "Memory allocation failed. Data not added." << std::endl;
        }
    }

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

int main() {
    ResourceManager rm;
    rm.addData(10);
    rm.addData(20);
    rm.addData(30);
    rm.displayData();
    return 0;
}
Back to exception_safety