Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 171 ยท Errors and Debugging

Error Handling Without Exceptions

Handle errors in C++ without exceptions - return codes, [[nodiscard]], std::optional, std::expected with and_then and transform, std::error_code, and how to choose.

Exceptions are C++'s built-in way to report failure, but they're not the only one, and in some fields they're not even allowed. Many game studios, embedded firmware teams and parts of the systems world compile with -fno-exceptions. Even in code that uses exceptions, a function like "parse this number" fails so often that throwing for every bad input would be clumsy and slow. For these cases C++ offers a range of tools that put the error in the return value, where the caller can't overlook it.

This lesson walks through them in historical order: plain error codes and output parameters, [[nodiscard]], std::optional for "maybe there's no value", std::expected (C++23) for "a value or a reason why not", and std::error_code for operating-system style errors. It ends with a practical guide for picking a strategy.

Error codes: the C tradition

The oldest approach is to return a status and pass the real result back through a reference or pointer parameter. C libraries do this everywhere, and you'll meet it whenever you call operating-system APIs.

C++ Status codes and an output parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Error codes are cheap, predictable and easy to understand. Their weaknesses are just as clear:

  • They're easy to ignore. Nothing forces the caller to look at the result.
  • The output parameter is awkward. You must create age before the call, invent a placeholder value, and it may stay uninitialized on failure.
  • Errors don't propagate by themselves. Every layer must check and pass the code upward, which buries the real logic under if (s != Status::Ok) return s;.

[[nodiscard]]: make ignoring an error a warning

The [[nodiscard]] attribute on parse_age solves the first problem. If a caller writes parse_age(input, age); and throws the status away, the compiler warns: ignoring return value of 'Status parse_age(...)', declared with attribute 'nodiscard'. Since C++20 you can add a reason, [[nodiscard("check the status")]], and you can put the attribute on a whole type (enum class [[nodiscard]] Status), so every function returning it is covered. Use it on every function whose return value is an error indicator.

errno

The C library has one more convention: functions such as std::strtol or std::fopen set the global (actually thread-local) variable errno from <cerrno> when they fail. You must set it to 0 before the call and check it right after, because any later library call may overwrite it. It's the least pleasant scheme of all, and new code shouldn't imitate it.

std::optional: a value or nothing

When there's only one way to fail and the reason is obvious, return std::optional<T> from <optional>. It either holds a T or is empty (std::nullopt). It replaces "magic" return values such as -1, nullptr or an empty string, which callers have to know about.

C++ std::optional for lookups that may fail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that "pear" has quantity 0 and "kiwi" has no quantity at all. A plain int return could never tell those apart. std::optional can't say why a value is missing, though. When the caller needs a reason, use std::expected. Both types are covered in full in std::optional, std::variant, std::any and std::expected.

std::expected: a value or an error (C++23)

std::expected<T, E> from <expected> holds either a T (the expected result) or an E (the error). You return the value normally and wrap errors in std::unexpected(...). It combines the explicitness of error codes with the convenience of a real return value, and it's the closest standard C++ gets to Rust's Result type.

C++ Parsing with std::expected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The interface reads naturally: if (result) checks for success, *result (or result.value()) gives the value, and result.error() gives the error. Calling .value() on an expected that holds an error throws std::bad_expected_access<E>, so be sure to check first, or use value_or(fallback).

Chaining steps with and_then, transform and or_else

The real strength of std::expected shows when several steps can each fail. C++23 gives it monadic operations that pass a success along and skip the remaining steps on the first error:

  • and_then(f): if there's a value, call f(value), which itself returns an expected.
  • transform(f): if there's a value, replace it with f(value), which returns a plain value.
  • or_else(f): if there's an error, call f(error) to recover or translate it.
  • transform_error(f): if there's an error, convert it into a different error type.
C++ A pipeline of fallible steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

There are no nested ifs. As soon as one step returns an error, the following and_then and transform calls are skipped and the error travels to the end, just like an exception would, but visible in the types. The example also shows a common pattern at the edge of your code: std::stoi throws, so parse_percent catches the exception and turns it into an expected error.

std::error_code: errors from the system

Operating-system and library errors such as "file not found" or "permission denied" have their own standard representation in <system_error>. A std::error_code is a small value holding an integer plus a pointer to an error category that knows how to explain that integer. A value-initialized error_code means success, so if (ec) reads as "if there was an error".

The portable condition names live in the enum std::errc: std::errc::no_such_file_or_directory, std::errc::permission_denied, std::errc::invalid_argument and many more. Two parts of the standard library you already know use these types:

  • std::from_chars returns a std::errc (shown in the parse_int example).
  • std::filesystem functions come in two versions: one throws std::filesystem::filesystem_error, the other takes a std::error_code& and never throws.
C++ std::error_code with the filesystem library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The numeric value (2 on Linux for "no such file") is platform-specific, so compare against std::errc constants instead of raw numbers. std::system_error is the exception type that carries an error_code; throw it when you want to turn a system error into an exception: throw std::system_error(ec, "opening config"). You'll use the filesystem library properly in The Filesystem Library.

Choosing a strategy

There's no single right answer, but there are good defaults:

Situation Good choice
A bug: a broken precondition that should never happen assert in development, a logic_error or termination in production
Rare failures deep in the call stack that only the top can handle (disk full, out of memory, corrupt file) Exceptions
Failures that are a normal, expected outcome (parsing user input, lookups, validation) std::expected, or std::optional when no reason is needed
Code built with -fno-exceptions (many game engines, embedded, some kernels) std::expected, error codes, [[nodiscard]]
Talking to the OS or C libraries std::error_code / std::errc, converted at the boundary
Constructors and operators, which can't return an error Exceptions, or a factory function returning std::expected<T, E>

Why do games and embedded systems avoid exceptions? Throwing is slow compared to a normal return (often microseconds, dominated by the unwinder looking up tables), its cost is hard to predict, and the tables add size to the binary. On a microcontroller with 64 KB of flash, or in a frame that must finish in 16 ms, that matters. On a desktop or server application where errors are rare, the "zero-cost" happy path of exceptions often makes them faster than checking codes everywhere.

Whatever you pick, a few principles hold:

  • Be consistent within a layer. A library that sometimes throws and sometimes returns codes for the same kind of problem is miserable to use.
  • Convert at boundaries. Wrap a C API's codes in an expected; catch a third-party exception and turn it into your own type. The example with std::stoi above does exactly this.
  • Never ignore an error silently. Use [[nodiscard]], return types that must be checked, and log what you deliberately drop.
  • Report bugs differently from runtime problems. A null pointer that "can't happen" is a bug for assertions; a missing file is a runtime condition the program should handle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function returns std::optional<int>. The caller writes int n = f().value_or(-1); and f() returns an empty optional. What is n?

    value_or returns the contained value if present and the fallback otherwise. Only value() throws, and only operator* on an empty optional is undefined behavior.
  2. 2. auto r = parse(text).and_then(validate).transform(double_it); The parse step returns an error. What happens?

    and_then and transform only call their function when there's a value. An error passes through the chain unchanged.
  3. 3. What does [[nodiscard]] on a function do?

    It is a compile-time diagnostic only. It's ideal for functions whose return value reports an error.
  4. 4. Why compare an error_code with std::errc::no_such_file_or_directory instead of with the number 2?

    Different operating systems use different numbers for the same problem. Comparing with std::errc works everywhere.
  5. 5. In which situation is std::expected usually a better fit than an exception?

    When failure is a normal outcome handled by the immediate caller, putting it in the return type is clearer and cheaper than throwing.

Summary

  • Error codes plus output parameters are cheap and universal but easy to ignore; [[nodiscard]] makes ignoring them a warning.
  • std::optional<T> replaces magic return values when the only failure is "no value".
  • std::expected<T, E> (C++23) returns a value or an error; and_then, transform, or_else and transform_error chain fallible steps without nested ifs.
  • std::error_code and std::errc represent operating-system errors portably; std::filesystem and std::from_chars use them, and std::system_error turns them into exceptions.
  • Use exceptions for rare failures handled far away, expected/optional for common, local failures, and stay consistent within each layer.

Next: Signal Handling.