Exception Safety

Exception guarantees and RAII

Interview Relevant: Robust code design

Exception Safety

Levels of exception safety guarantees.

Code Examples

Exception safety guarantees and patterns.

cpp
1// Exception safety levels:
2// 1. No-throw: Never throws (noexcept)
3// 2. Strong: If exception thrown, state unchanged
4// 3. Basic: No leaks, invariants maintained
5// 4. No guarantee: May leak, corrupt state
6
7// Strong guarantee with copy-and-swap
8class Widget {
9    int* data;
10public:
11    Widget& operator=(Widget other) noexcept {
12        swap(*this, other);  // Never throws
13        return *this;
14    }  // Old data cleaned up when other destroyed
15};
16
17// Basic guarantee with RAII
18void process() {
19    auto ptr = make_unique<Resource>();  // RAII
20    riskyOperation();  // If throws, ptr still cleaned up
21}
22
23// Commit-or-rollback pattern
24void transfer(Account& from, Account& to, int amount) {
25    from.withdraw(amount);  // May throw
26    try {
27        to.deposit(amount);
28    } catch (...) {
29        from.deposit(amount);  // Rollback
30        throw;
31    }
32}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In