← C++

C++ · 17 / 24

Error handling and the strong exception guarantee

Separate expected validation failures from exceptions and preserve the previous state when a batch update fails.

  • Large
  • Advanced
  • 90 min

Prerequisites: Headers, CMake and first unit tests, Ownership, lifetime and move semantics

In this tutorial
  1. Represent success and failure as types
  2. Validate before committing
  3. Handle the error at the call site
  4. Compare state after failures
  5. Trigger an exception during processing
  6. State guarantees precisely
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20, CMake 3.25 or later, CTest and Python 3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. No additional libraries are required. The documented commands were checked on Linux.

Verified on 2026-10-21 on Linux x86_64. Validation failures, typed error codes, preserved data after rejection and an injected exception, plus successful batch commit. No real out-of-memory test.

An import must not replace the first orders and then fail on an invalid record. We validate the whole input, construct a complete candidate and commit at a clear boundary. A typed result represents expected failures. The algorithm's structure preserves the original batch when an exception occurs before the commit.

Package contents and individual files

01Represent success and failure as types

Result<T> is a std::variant of a value and Error. Error contains a stable code and an explanatory message. Successful operations without a value return Done. Callers check succeeded before reading a value. Invalid user input is ordinary control flow in this design.

result.hpp · cppOpen file
#pragma once
#include <string>
#include <variant>

namespace orders {
enum class ErrorCode { invalid, duplicate, storage, unsupported };
struct Error {
  ErrorCode code;
  std::string message;
};
template <class T> using Result = std::variant<T, Error>;
using Done = std::monostate;
template <class T> bool succeeded(const Result<T> &result) {
  return std::holds_alternative<T>(result);
}
} // namespace orders
Expected result

Duplicates can be distinguished through ErrorCode::duplicate.

02Validate before committing

validateBatch checks at most 1000 orders, unique IDs, titles of 1 to 80 UTF-8 bytes, priorities from 0 to 2 and valid statuses. replaceValidated then copies into a candidate. swap commits it without another allocation. If an earlier allocation fails, current remains intact.

order.hpp · cppOpen file
#pragma once
#include "result.hpp"
#include <algorithm>
#include <ranges>
#include <set>
#include <span>
#include <string_view>
#include <vector>

namespace orders {
enum class Status { open, done };
struct Order {
  int id;
  std::string title;
  int priority{0};
  Status status{Status::open};
  bool operator==(const Order &) const = default;
};
inline Result<Done> validate(const Order &order) {
  const bool blank = std::ranges::all_of(order.title, [](char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  });
  if (order.id < 1 || order.id > 1000000 || order.title.empty() ||
      order.title.size() > 80 || blank || order.priority < 0 ||
      order.priority > 2 ||
      (order.status != Status::open && order.status != Status::done))
    return Error{ErrorCode::invalid, "ID 1..1000000, title 1..80 UTF-8 bytes, "
                                     "priority 0..2 and valid status required"};
  return Done{};
}
inline Result<Done> validateBatch(std::span<const Order> batch) {
  if (batch.size() > 1000)
    return Error{ErrorCode::invalid, "At most 1000 orders are allowed"};
  std::set<int> ids;
  for (const auto &order : batch) {
    auto result = validate(order);
    if (!succeeded(result))
      return std::get<Error>(result);
    if (!ids.insert(order.id).second)
      return Error{ErrorCode::duplicate, "Duplicate order ID"};
  }
  return Done{};
}
inline std::vector<int> matchingIds(std::span<const Order> values,
                                    std::string_view needle) {
  // Both views borrow their input. Consume them before the owner changes.
  auto matching =
      values | std::views::filter([needle](const Order &order) {
        return order.status == Status::open &&
               order.title.find(needle) != std::string::npos;
      }) |
      std::views::transform([](const Order &order) { return order.id; });
  return {matching.begin(), matching.end()};
}
inline Result<Done> replaceValidated(std::vector<Order> &current,
                                     std::span<const Order> incoming) {
  auto result = validateBatch(incoming);
  if (!succeeded(result))
    return std::get<Error>(result);
  std::vector<Order> candidate(incoming.begin(), incoming.end());
  // Validation and allocations precede this non-throwing commit point.
  current.swap(candidate);
  return Done{};
}
} // namespace orders
Expected result

After a validation failure the original vector is unchanged.

03Handle the error at the call site

The demo tries to commit an order without a title. It prints the error and then the number of orders still stored. An empty valid list is an explicit clearing operation, not an error. The interface must eventually communicate this distinction too.

main.cpp · cppOpen file
#include "test_support.hpp"
int main() {
  auto current = samples();
  std::vector<orders::Order> invalid{{1, ""}};
  auto result = orders::replaceValidated(current, invalid);
  if (auto *error = std::get_if<orders::Error>(&result))
    std::cout << error->message << '\n';
  std::cout << "Still saved: " << current.size() << '\n';
}
Expected result

The last line is Still saved: 3.

04Compare state after failures

Tests retain the original batch before failure attempts. They check duplicates, blank titles and invalid priorities. In addition to the error code, current == before is essential. A test that merely expects an error would miss partial changes.

tests.cpp · cppOpen file
#include "test_support.hpp"
int main() {
  auto current = samples();
  const auto before = current;
  auto incoming = samples();
  incoming[1].id = incoming[0].id;
  auto result = orders::replaceValidated(current, incoming);
  require(!orders::succeeded(result), "duplicate rejected");
  require(std::get<orders::Error>(result).code == orders::ErrorCode::duplicate,
          "typed error");
  require(current == before, "validation failure preserves old state");
  incoming = samples();
  incoming[0].title = "   ";
  require(!orders::succeeded(orders::replaceValidated(current, incoming)),
          "blank title");
  incoming[0].title = "New order";
  incoming[0].priority = 3;
  require(!orders::succeeded(orders::replaceValidated(current, incoming)),
          "priority bounds");
  require(current == before, "all failures preserve state");
  require(orders::succeeded(orders::replaceValidated(current, {})),
          "empty replacement valid");
  require(current.empty(), "empty replacement clears explicitly");
  std::cout << "validation and commit checks passed\n";
}
Expected result

Every rejected batch preserves the original contents.

05Trigger an exception during processing

The exercise renames orders using a supplied function. That function may throw on the second order. The solution therefore works on a copy and commits only after all renames and validation succeed. It does not swallow the exception. The test catches it at its outer boundary and checks that the batch is unchanged.

solution.cpp · cppOpen file
#include "test_support.hpp"
#include <functional>
orders::Result<orders::Done>
renameBatch(std::vector<orders::Order> &current,
            const std::function<std::string(const orders::Order &)> &rename) {
  auto candidate = current;
  for (auto &order : candidate)
    order.title = rename(order);
  return orders::replaceValidated(current, candidate);
}
int main() {
  auto current = samples();
  const auto before = current;
  bool threw = false;
  try {
    renameBatch(current, [](const auto &order) -> std::string {
      if (order.id == 2)
        throw std::runtime_error("formatter unavailable");
      return "Changed";
    });
  } catch (const std::runtime_error &) {
    threw = true;
  }
  require(threw && current == before, "exception preserves whole batch");
  require(
      !orders::succeeded(renameBatch(current, [](const auto &) { return ""; })),
      "invalid result rejected");
  require(current == before, "validation preserves whole batch");
  require(
      orders::succeeded(renameBatch(
          current, [](const auto &order) { return "Ready: " + order.title; })),
      "commit valid rename");
  require(current[0].title == "Ready: Deliver motors", "new title");
}
Expected result

A failure on the second title leaves no partially renamed first order.

06State guarantees precisely

Build with python3 verify.py. The test triggers a controlled exception rather than actual operating-system memory exhaustion. The strong guarantee follows from constructing a candidate and committing through non-throwing swap. This claim applies to this operation, not automatically to every program function.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(cpp_17 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
enable_testing()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
  add_compile_options(-Wall -Wextra -Wpedantic -Werror)
endif()
add_executable(order_lab main.cpp)
add_executable(lesson_tests tests.cpp)
add_test(NAME lesson_tests COMMAND lesson_tests)
set_tests_properties(lesson_tests PROPERTIES TIMEOUT 30)
add_executable(exercise_solution solution.cpp)
add_test(NAME exercise_solution COMMAND exercise_solution)
set_tests_properties(exercise_solution PROPERTIES TIMEOUT 30)
Expected result

The example and rename solution pass CTest.

Your exercise

Implement renameBatch with a supplied renaming function. A failure on the second order or an invalid new title must preserve every old title. Also add a successful run.

Show the solution and explanation

The solution copies the batch, invokes the renamer only on that candidate and uses replaceValidated for the final commit. Tests separately cover an exception, validation failure and successful commit.

solution.cpp · cppOpen file
#include "test_support.hpp"
#include <functional>
orders::Result<orders::Done>
renameBatch(std::vector<orders::Order> &current,
            const std::function<std::string(const orders::Order &)> &rename) {
  auto candidate = current;
  for (auto &order : candidate)
    order.title = rename(order);
  return orders::replaceValidated(current, candidate);
}
int main() {
  auto current = samples();
  const auto before = current;
  bool threw = false;
  try {
    renameBatch(current, [](const auto &order) -> std::string {
      if (order.id == 2)
        throw std::runtime_error("formatter unavailable");
      return "Changed";
    });
  } catch (const std::runtime_error &) {
    threw = true;
  }
  require(threw && current == before, "exception preserves whole batch");
  require(
      !orders::succeeded(renameBatch(current, [](const auto &) { return ""; })),
      "invalid result rejected");
  require(current == before, "validation preserves whole batch");
  require(
      orders::succeeded(renameBatch(
          current, [](const auto &order) { return "Ready: " + order.title; })),
      "commit valid rename");
  require(current[0].title == "Ready: Deliver motors", "new title");
}

Project context and sources

Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.