Tutorials / C++: From Basics to Modern C++ / Error handling: exceptions, optional and expected

Error handling: exceptions, optional and expected

17 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

Things go wrong

Files are missing. Users type letters where numbers were expected. Networks drop. A program that ignores this works in the demo and fails in production. C++ gives you several ways to report and handle errors, and the skill is picking the right one for each situation.

Exceptions

An exception is an object that you throw when a function cannot do what it promised. The stack unwinds, destroying local objects (this is where RAII earns its keep), until a matching catch block is found.

#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

std::vector<std::string> readLines(const std::string& path) {
    std::ifstream in{path};
    if (!in) {
        throw std::runtime_error("cannot open file: " + path);
    }
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(in, line)) lines.push_back(line);
    return lines;
}

int main() {
    try {
        auto lines = readLines("data.txt");
        std::cout << lines.size() << " lines\n";
    } catch (const std::runtime_error& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
}

Catch by const reference. Catching by value copies the exception and can slice a derived exception down to its base class. The standard exceptions all derive from std::exception, which provides what(). The useful ones: std::invalid_argument for bad inputs, std::out_of_range for bad indexes, std::runtime_error for failures that could not be foreseen from the arguments, and std::logic_error for bugs in the calling code.

Your own exception types

class ParseError : public std::runtime_error {
public:
    ParseError(const std::string& msg, int line)
        : std::runtime_error{msg + " (line " + std::to_string(line) + ")"}, line_{line} {}
    int line() const { return line_; }
private:
    int line_;
};

// throw ParseError{"missing comma", 12};

Order catch blocks from the most specific to the most general. A catch (...) block catches anything, which is useful at the top of a program or a thread, to log and exit cleanly, but not as a habit in the middle of the code.

When exceptions are the right tool

Use exceptions for errors that are unexpected at the call site and that the immediate caller cannot sensibly handle: the file that should exist does not, memory ran out, a constructor cannot build a valid object. Constructors have no return value, so exceptions are the only clean way to report a failure there.

Do not use exceptions for ordinary control flow. "The user typed a name that is not in the list" is not exceptional. It is a normal outcome, and you want a normal return value.

std::optional: a value that may be missing

When "no result" is a normal answer, return std::optional<T>. It holds either a T or nothing.

#include <optional>
#include <string>
#include <vector>

struct User { int id; std::string name; };

std::optional<User> findUser(const std::vector<User>& users, int id) {
    for (const auto& u : users) {
        if (u.id == id) return u;
    }
    return std::nullopt;
}

int main() {
    std::vector<User> users{{1, "Asha"}, {2, "Bilal"}};

    if (auto u = findUser(users, 2)) {
        std::cout << u->name << "\n";
    } else {
        std::cout << "no such user\n";
    }
    std::cout << findUser(users, 9).value_or(User{0, "guest"}).name << "\n";
}

The type documents the possibility of absence, and callers cannot forget to check as easily as they can with a null pointer. value_or supplies a default. Calling value() on an empty optional throws std::bad_optional_access, while dereferencing an empty optional with * is undefined behaviour, so check first.

std::expected: a value or an error

C++23 adds std::expected<T, E>. It holds either the successful value or an error value that says what went wrong. It suits operations like parsing, where failure is common and you want a reason, not just "nothing".

#include <charconv>
#include <expected>
#include <string>
#include <string_view>

enum class ParseFail { Empty, NotANumber };

std::expected<int, ParseFail> parseInt(std::string_view text) {
    if (text.empty()) return std::unexpected{ParseFail::Empty};
    int value{};
    auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (ec != std::errc{} || end != text.data() + text.size())
        return std::unexpected{ParseFail::NotANumber};
    return value;
}

int main() {
    auto r = parseInt("123");
    if (r) std::cout << *r << "\n";
    else   std::cout << "parse failed\n";
}

This needs a compiler and standard library that supports C++23 <expected>. Recent GCC, Clang and MSVC releases do, but check yours, since support depends on the version. If you do not have it, std::optional or a small struct holding a value and an error code does the same job.

Exception safety

When a function throws, what state is your data left in? There are three levels worth knowing.

  • Basic guarantee: nothing leaks and the object is still valid, though its value may have changed.
  • Strong guarantee: the operation either completes or has no effect, as if it never ran.
  • No-throw guarantee: it never throws. Mark such functions noexcept.

RAII gives you the basic guarantee almost for free. For the strong guarantee, a common technique is to do the risky work on a copy and then swap it in with a no-throw operation. Move operations and destructors should be noexcept. If an exception escapes from a noexcept function, the program calls std::terminate.

Choosing

SituationTool
Constructor cannot build a valid objectException
Lookup may legitimately find nothingstd::optional
Operation fails often and you need the reasonstd::expected or an error code
Cannot recover at allLog and exit

The common mistake

Swallowing errors with an empty catch (...) {}. The program carries on in an unknown state and fails later in a place nobody can trace. The second mistake is manual cleanup next to a throw, such as new followed by delete with a throwing call between them. The third is throwing from a destructor.

Try it yourself

  1. Write double safeDivide(double a, double b) that throws std::invalid_argument when b is zero, and a main that handles it.
  2. Write std::optional<double> parseDouble(const std::string&) using std::stod inside a try block, returning nullopt on failure.
  3. Make a custom exception InsufficientFunds that carries the shortfall amount, and use it in the BankAccount class from an earlier lesson.
cpp
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

std::vector<std::string> readLines(const std::string& path) {
    std::ifstream in{path};
    if (!in) {
        throw std::runtime_error("cannot open file: " + path);
    }
    std::vector<std::string> lines;
    std::string line;
    while (std::getline(in, line)) lines.push_back(line);
    return lines;
}

int main() {
    try {
        auto lines = readLines("data.txt");
        std::cout << lines.size() << " lines\n";
    } catch (const std::runtime_error& e) {
        std::cerr << "error: " << e.what() << "\n";
        return 1;
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account