Skip to main content

Lesson 5 of 5

Practice & Quiz - Error Handling & File I/O

Test your understanding of exception hierarchy, exception safety guarantees, noexcept, fstream, and std::filesystem with a practical exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Config File with Strong Exception Safety

Practical Exercise - Config File with Strong Exception Safety
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <stdexcept>
#include <filesystem>
#include <optional>

namespace fs = std::filesystem;

class ConfigError : public std::runtime_error {
    std::string key_;
public:
    ConfigError(const std::string& key, const std::string& msg)
        : std::runtime_error("Config[" + key + "]: " + msg)
        , key_(key) {}
    const std::string& key() const { return key_; }
};

class Config {
    std::unordered_map<std::string, std::string> data_;
    fs::path path_;

public:
    explicit Config(fs::path p) : path_(std::move(p)) {}

    void load() {
        if (!fs::exists(path_)) return;  // empty config is OK
        std::ifstream f(path_);
        if (!f) throw std::runtime_error("Cannot open: " + path_.string());
        std::string line;
        size_t lineno = 0;
        while (std::getline(f, line)) {
            ++lineno;
            if (line.empty() || line[0] == '#') continue;
            auto eq = line.find('=');
            if (eq == std::string::npos)
                throw ConfigError(std::to_string(lineno), "Missing '=' on line");
            data_[line.substr(0, eq)] = line.substr(eq + 1);
        }
    }

    // Strong guarantee: write to temp, rename atomically
    void save() const {
        fs::path tmp = path_.string() + ".tmp";
        try {
            std::ofstream f(tmp);
            if (!f) throw std::runtime_error("Cannot write: " + tmp.string());
            for (const auto& [k, v] : data_)
                f << k << "=" << v << "\n";
            if (!f) throw std::runtime_error("Write error");
            f.close();
            fs::rename(tmp, path_);  // atomic - strong guarantee
        } catch (...) {
            if (fs::exists(tmp)) fs::remove(tmp);
            throw;
        }
    }

    std::optional<std::string> get(const std::string& key) const {
        auto it = data_.find(key);
        return it == data_.end() ? std::nullopt : std::optional<std::string>(it->second);
    }
    void set(std::string key, std::string val) { data_[std::move(key)] = std::move(val); }
    void remove(const std::string& key) { data_.erase(key); }
};

int main() {
    Config cfg("test_config.ini");
    cfg.set("host", "localhost");
    cfg.set("port", "8080");
    cfg.set("debug", "true");
    cfg.save();

    Config cfg2("test_config.ini");
    cfg2.load();

    for (const std::string& k : {"host", "port", "debug", "missing"}) {
        auto v = cfg2.get(k);
        std::cout << k << " = " << v.value_or("(not set)") << "\n";
    }

    fs::remove("test_config.ini");
    return 0;
}

Module Quiz

Module Quiz
Question 1 of 5

Why should you ALWAYS catch exceptions by `const` reference?

Tip

Tip

Practice Practice Quiz Error Handling File IO in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Exception Hierarchies, noexcept Guarantees, Exception Safety Levels & std::filesystem

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Error Handling File IO from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Error Handling File IO is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Topics in This Module

0/5 done