Module 5 · Errors and undefined behavior
5.2optional and expected for errors
Return a failure as part of the result: std::optional when there's simply no answer, std::expected when the caller needs to know what went wrong. Chain steps with and_then, transform and or_else, and choose between these and exceptions.
On this page
- Key terms
- In 30 seconds
- std::optional: maybe no answer
- std::expected: a value or an error
- Error enums: errors the caller can act on
- Getting the value out
- Chaining steps: and_then, transform and or_else
- Which one should I use?
- Under the hood
- Common pitfalls
- Returning the error without std::unexpected
- Calling value() on an error
- Using * without checking
- Try it yourself
Key terms
std::expected<T, E>- Holds either a value of type
Tor an error of typeE. From<expected>, new in C++23. std::unexpected(e)- Wraps an error so it can be returned as a
std::expected:return std::unexpected(BaseError::ambiguous);. - error enum
- An
enum classthat lists the ways a function can fail, so callers can react to each one. It's one common choice for theEinstd::expected<T, E>; a message string is another. error()andvalue()error()gives the error stored in astd::expected; only call it when there is no value.value()gives the value, or throws an exception if there's none (std::bad_expected_accessfor astd::expected).and_then- Runs the next step, which can itself fail, only if there's a value. An error skips it and passes through.
transform- Changes the value with a step that can't fail, if there is one. An error passes through unchanged.
or_else- Runs a step only if there's an error: to recover from it, report it or swap it for another.
Exceptions suit failures that are rare and handled far away. Many failures aren’t like that: a field that doesn’t parse, a search that finds nothing, a base that isn’t A, C, G or T. Those are ordinary results, and the caller right above wants to deal with them. Returning the failure as part of the result puts it in the function’s type, so the caller can’t miss that it might happen.
In 30 seconds
std::optional<T>holds aTor nothing. Use it when “no answer” needs no explanation.std::expected<T, E>(C++23,<expected>) holds aTor an errorEthat says what went wrong. Returnstd::unexpected(error)for the error.- Check with
if (r)before you use*r, and read the error withr.error(). and_then,transformandor_elsechain steps; the first error skips the steps that need a value.
std::optional: maybe no answer
optional, variant and tuple introduced std::optional. It’s the simplest way to say “this can fail” when there’s only one way to fail. A search either finds something or it doesn’t:
#include <optional>
#include <print>
#include <string>
std::optional<std::size_t> find_start_codon(const std::string& dna) {
std::size_t at = dna.find("ATG");
if (at == std::string::npos) {
return std::nullopt;
}
return at;
}
int main() {
if (auto pos = find_start_codon("CCATGGA")) {
std::println("start codon at {}", *pos);
}
std::optional<std::size_t> none = find_start_codon("CCCGGA");
std::println("found: {}", none.has_value());
}Output
start codon at 2 found: false
std::nullopt means “no value”. if (auto pos = …) declares pos and tests it in one step: the body runs only if there is a value. To get the position out, the caller has to unwrap the optional, which is a reminder to check first. But an empty optional says nothing about why it’s empty. When there are several reasons and the caller cares which one, you need the error too.
std::expected: a value or an error
std::expected<T, E> holds either a T (the expected case) or an E that describes what went wrong. A function returns a plain value for success; for failure it wraps the error in std::unexpected(…):
#include <array>
#include <expected>
#include <format>
#include <print>
#include <string>
#include <string_view>
std::expected<int, std::string> parse_quality(std::string_view text) {
if (text.empty()) {
return std::unexpected("empty field");
}
int value = 0;
for (char c : text) {
if (c < '0' || c > '9') {
return std::unexpected(std::format("{} is not a number", text));
}
value = value * 10 + (c - '0');
if (value > 93) {
return std::unexpected("quality above 93");
}
}
return value;
}
int main() {
std::array<std::string_view, 4> fields = {"30", "3x", "", "120"};
for (std::string_view field : fields) {
std::expected<int, std::string> q = parse_quality(field);
if (q.has_value()) {
std::println("quality {}", *q);
} else {
std::println("error: {}", q.error());
}
}
}Output
quality 30 error: 3x is not a number error: empty field error: quality above 93
The function’s type now says it can fail and what an error looks like. has_value() (or if (q)) tells you which case you have; *q gives the value and q.error() gives the error. c - '0' turns a digit character into its number, and the check against 93 inside the loop stops value from ever overflowing.
Error enums: errors the caller can act on
A message is good for people. When code has to react differently to each failure, list the reasons in an error enum, an enum class (enum class covers them). Here an N (a base the sequencer couldn’t call) is skipped quietly, but any other letter is reported:
#include <expected>
#include <print>
#include <string>
enum class BaseError { ambiguous, not_a_base };
std::expected<int, BaseError> base_code(char base) {
switch (base) {
case 'A':
return 0;
case 'C':
return 1;
case 'G':
return 2;
case 'T':
return 3;
case 'N':
return std::unexpected(BaseError::ambiguous);
default:
return std::unexpected(BaseError::not_a_base);
}
}
int main() {
std::string read = "GANTX";
for (char base : read) {
std::expected<int, BaseError> code = base_code(base);
if (code) {
std::println("{} -> {}", base, *code);
} else if (code.error() == BaseError::not_a_base) {
std::println("{} is not a base", base);
}
}
}Output
G -> 2 A -> 0 T -> 3 X is not a base
Getting the value out
There are three ways to read a std::expected, and the same three work on a std::optional:
#include <expected>
#include <print>
std::expected<int, char> ok = 30;
std::expected<int, char> bad = std::unexpected('x');
if (ok) {
std::println("checked: {}", *ok);
}
std::println("with a default: {}", bad.value_or(0));
try {
std::println("value(): {}", bad.value());
} catch (const std::bad_expected_access<char>& e) {
std::println("value() threw, the error is {}", e.error());
}Output
checked: 30 with a default: 0 value() threw, the error is x
if (r)then*r: check, then use. The usual way.r.value_or(fallback): the value, orfallbackif there’s an error.r.value(): the value, or a thrownstd::bad_expected_accessif there’s an error. Use it when an error here would be a surprise that an exception handler further up should deal with.
Chaining steps: and_then, transform and or_else
Real work is several steps, any of which can fail. Writing if (!r) return std::unexpected(r.error()); after each one gets repetitive. Three member functions do that check for you. Each takes a function to run (here, the name of one):
r.and_then(f): ifrhas a value, callf(value), which returns anotherstd::expectedwith the same error type. Ifrhas an error, skipfand keep the error.r.transform(f): ifrhas a value, replace it withf(value). Use it for a step that can’t fail.r.or_else(f): ifrhas an error, callf(error), which returns astd::expectedwith the same value type. Use it to recover, or to report and pass the error on.
Here a quality score is checked against the valid range, then against a minimum, and then converted into the probability that the base call is wrong (a Phred score q means a probability of 10−q/10; std::pow(10.0, x) from <cmath> computes 10 to the power x):
#include <array>
#include <cmath>
#include <expected>
#include <print>
#include <string>
std::expected<int, std::string> check_range(int q) {
if (q < 0 || q > 93) {
return std::unexpected(std::to_string(q) + " is not a quality score");
}
return q;
}
std::expected<int, std::string> check_usable(int q) {
if (q < 20) {
return std::unexpected(std::to_string(q) + " is too low to use");
}
return q;
}
double error_probability(int q) {
return std::pow(10.0, -q / 10.0);
}
std::expected<double, std::string> report(const std::string& error) {
std::println("skipped: {}", error);
return std::unexpected(error);
}
int main() {
std::array<int, 4> scores = {30, 10, 120, 20};
for (int q : scores) {
double p = check_range(q)
.and_then(check_usable)
.transform(error_probability)
.or_else(report)
.value_or(1.0);
std::println("{}: {}", q, p);
}
}Output
30: 0.001 skipped: 10 is too low to use 10: 1 skipped: 120 is not a quality score 120: 1 20: 0.01
Read the chain top to bottom as the happy path. For 10, check_usable fails, so transform is skipped, or_else reports the error, and value_or turns the error into the fallback 1.0 (treat the base as certainly wrong). No step had to check for an error by hand. To change the error instead of the value, use transform_error, the mirror image of transform.
Modern C++optional has them too
Since C++23, std::optional also has and_then, transform and or_else. They work the same way, with “no value” in place of an error.
Which one should I use?
Is it a bug: a rule your own code should never break?
YesNoNot an error to report: check it with
assertUndefined behavior, assertions and sanitizers covers it.Is no answer an ordinary result, with only one possible reason?
YesNoReturn
std::optional<T>Like a search that finds nothing.Is the failure rare, and only code far up the call chain can do anything about it?
YesNoThrow an exceptionLike a missing config file at startup, or running out of memory.
Otherwise: Return
std::expected<T, E>, with an error enum or a message asE
| What | When | Why | How |
|---|---|---|---|
std::optional<T> | “Nothing” is a normal answer with one obvious reason: not found, no more input. | The simplest type that can’t be used without checking. | return std::nullopt; |
std::expected<T, E> | Failure is a normal outcome and the caller, close by, needs to know why: parsing, validating, looking up. | The error is part of the type; no hidden jumps; cheap even when failures are common. | return std::unexpected(BaseError::ambiguous); |
| Exception | Failure is rare and must cross many functions: a missing file at startup, out of memory. | Code in between stays free of error checks, and it’s the only way a constructor can report failure. | throw std::runtime_error("…"); |
Rule of thumb: return std::expected when the caller should handle the failure right away, std::optional when there’s nothing to explain, and throw when only code far away can react.
Under the hood
A std::expected never allocates: the standard requires the value or the error to live inside the object itself. Only one of them exists at a time, so they share the same bytes, and GCC’s library puts a flag after them that says which one is there. Returning one is a plain return; there’s no unwinding and no tables. The cost is a test of the flag in every caller, whether or not anything failed.
#include <expected>
#include <optional>
#include <print>
enum class BaseError { ambiguous, not_a_base };
int main() {
std::println("int: {} bytes", sizeof(int));
std::println("optional<int>: {} bytes", sizeof(std::optional<int>));
std::println("expected<int, BaseError>: {} bytes",
sizeof(std::expected<int, BaseError>));
std::println("expected<double, BaseError>: {} bytes",
sizeof(std::expected<double, BaseError>));
}Output
int: 4 bytes optional<int>: 8 bytes expected<int, BaseError>: 8 bytes expected<double, BaseError>: 16 bytes
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
expected<int, BaseError> | value or error4 bytes | flag1 byte · tag | padding3 bytes | 8 bytes | |||||||||||||
expected<double, BaseError> | value or error8 bytes | flag1 byte · tag | padding7 bytes | 16 bytes | |||||||||||||
std::expected<int, BaseError> is 8 bytes on this platform: 4 bytes that hold either the int value or the BaseError (an enum class whose underlying type is int), 1 byte for the flag that says which, and 3 bytes of padding. std::expected<double, BaseError> is 16 bytes: 8 bytes for the double or the error, 1 flag byte and 7 bytes of padding.
The padding rounds the size up so that, in an array of these, the next value still starts at a suitable address: a multiple of 4 for an int, of 8 for a double. A small error type, like an enum, keeps std::expected small. A std::string error makes every result at least as big as a string, even the successful ones.
PerformanceCheap failures
Returning an error from a std::expected costs about the same as returning a value. Throwing an exception costs far more. When failures are frequent, such as bad records in a large input file, std::expected keeps the slow path fast.
Common pitfalls
Returning the error without std::unexpected
A function returning std::expected<int, BaseError> can’t return a BaseError directly. If it could, std::expected<int, int> would have no way to tell a value from an error. The compiler refuses:
#include <expected>
enum class BaseError { ambiguous, not_a_base };
std::expected<int, BaseError> base_code(char base) {
if (base == 'N') {
return BaseError::ambiguous;
}
return 0;
}
int main() {
return base_code('A').value();
}The compiler rejects this
main.cpp: In function ‘std::expected<int, BaseError> base_code(char)’:
main.cpp:7:27: error: could not convert ‘BaseError::ambiguous’ from ‘BaseError’ to ‘std::expected<int, BaseError>’
7 | return BaseError::ambiguous;
| ~~~~~~~~~~~^~~~~~~~~
| |
| BaseErrorWrite return std::unexpected(BaseError::ambiguous);.
Calling value() on an error
value() throws when there’s no value. If nothing catches it, the program ends like any other uncaught exception:
#include <expected>
#include <print>
enum class BaseError { ambiguous, not_a_base };
std::expected<int, BaseError> base_code(char base) {
if (base == 'A') {
return 0;
}
return std::unexpected(BaseError::not_a_base);
}
int main() {
std::println("{}", base_code('X').value());
}This fails when it runs
terminate called after throwing an instance of 'std::bad_expected_access<BaseError>' what(): bad access to std::expected without expected value
Check with if (r) first, or use value_or when there’s a sensible fallback.
Using * without checking
*r doesn’t check. On an error (or an empty optional), it’s undefined behavior. GCC’s standard library turns on its own checks in builds without optimization, like this one, so here the program stops with a failed assertion instead of reading garbage. An optimized build, or another standard library, may print anything:
#include <expected>
#include <print>
std::expected<int, char> bad = std::unexpected('x');
int quality = *bad;
std::println("{}", quality);This fails when it runs
/usr/include/c++/15/expected:731: constexpr _Tp& std::expected<_Tp, _Er>::operator*() & [with _Tp = int; _Er = char]: Assertion '_M_has_value' failed.
Always check before *. Undefined behavior, assertions and sanitizers says more about these library checks.
Try it yourself
Try it yourself
A k-mer counter reads its k (the length of each piece of DNA it counts) from the user. A useful k is between 1 and 32. Change parse_kmer_size to return std::expected<int, std::string>, with the errors "k must be at least 1" and "k must be at most 32", and make main print k = 21 or error: … for each input.
#include <array>
#include <print>
int parse_kmer_size(int k) {
return k;
}
int main() {
std::array<int, 3> inputs = {21, 0, 40};
for (int k : inputs) {
std::println("k = {}", parse_kmer_size(k));
}
}Expected output
k = 21 error: k must be at least 1 error: k must be at most 32
Show a hint
Return std::unexpected(…) with a different message for each problem. In main, test the result with if (r), print *r on success and r.error() on failure.
Show a solution
#include <array>
#include <expected>
#include <print>
#include <string>
std::expected<int, std::string> parse_kmer_size(int k) {
if (k < 1) {
return std::unexpected("k must be at least 1");
}
if (k > 32) {
return std::unexpected("k must be at most 32");
}
return k;
}
int main() {
std::array<int, 3> inputs = {21, 0, 40};
for (int k : inputs) {
std::expected<int, std::string> r = parse_kmer_size(k);
if (r) {
std::println("k = {}", *r);
} else {
std::println("error: {}", r.error());
}
}
}parse_kmer_size returns std::expected<int, std::string>: a plain int for a good value and std::unexpected(message) for each kind of bad one. The caller checks which case it has before using the value, so 0 and -3 are never used as sizes.
Saved in this browser only.