CodeBlanks Logo Icon CodeBlanks

Summary - Advanced error handling

Combine exception safety, RAII and std::expected to write a safe class.

Summary - Advanced error handling

In this group you learned exception hierarchy, exception safety, RAII, std::expected and noexcept.

Exceptions are organised in the std::exception hierarchy; safety guarantees (basic, strong, nothrow) are the basis of robust code; RAII ties resources to objects; std::expected returns errors as values; the noexcept contract gives a no-throw guarantee. Now you will write a SafeStack class that combines these ideas: it will manage data with RAII, return std::expected from pop, and mark empty as noexcept.

Practice Write a SafeStack class

Write a SafeStack class: it has a std::vector<int> data_ member; void push(int v) adds; std::expected<int, std::string> pop() returns std::unexpected(std::string("empty stack")) when empty, otherwise the value; bool empty() const noexcept returns data_.empty(). In main call s.push(42), auto r = s.pop() and if r.has_value() print r.value().

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <expected>
#include <string>

// Write the SafeStack class: push, pop (expected), empty (noexcept)

int main() {
    // Create a stack, add a value, pop it and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <expected>
#include <string>

class SafeStack {
    std::vector<int> data_;
public:
    void push(int v) { data_.push_back(v); }
    std::expected<int, std::string> pop() {
        if (data_.empty()) return std::unexpected(std::string("empty stack"));
        int v = data_.back();
        data_.pop_back();
        return v;
    }
    bool empty() const noexcept { return data_.empty(); }
};

int main() {
    SafeStack s;
    s.push(42);
    auto r = s.pop();
    if (r.has_value()) std::cout << r.value();
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 the SafeStack pop call

Question
auto r = s.____();
Answer
auto r = s.pop();

Explanation: s.pop() returns std::expected.

2 Match each idea to its description

Term Meaning
hierarchy Exception tree
safety Guarantee level
RAII Resource tied to object
expected Error as value

3 Which idea returns errors as values instead of exceptions?

  • RAII
  • std::expected Correct answer
  • noexcept
  • hierarchy

Explanation: std::expected gives the error as a return value.

All lessons in Advanced