std::expected

std::expected is a way of handling errors in C++. It presents an object which either has an expected value, or an error in case something unexpected happens.

std::expected<int, std::string>

std::expected is currently a proposal to C++, and in order to use it you’d have to pick one of the existing implementations yourself:

In my example I chose the single-header implementation expected-lite. Installing it is very easy, you can just put the header next to your main.cpp, or as I did it, in a nonstd subdirectory.

And here is how to use it

In this simple example, we have a method doSomething() and we expect it to return a double if everything goes well.

In case of an error, we don’t really expect the return value to be correct, it might be corrupted or otherwise wrong. Instead, we’d like to know what happened. Correct? In that case we actually expect an error.

This behaviour is exactly what std::expected does. Have a look:

#include "nonstd/expected.hpp"

nonstd::expected<double, std::string> doSomething() {
  // here we do something ..
  double frequency = calculateFrequency();
  // and try to detect an error:
  if (!frequency) {
    return nonstd::make_unexpected("Could not calculate frequency");
  }
  return {frequency};
}
..
auto calculatedFrequency = doSomething();
if (!calculatedFrequency) {
  std::cout << *calculatedFrequency << std::endl;
}

We wrap our return type into expected<> together with a string, which is our type for the error. In case of an error, call make_unexpected() with the error message.

Otherwise use the { value } syntax to pack the value if everything is fine.

It also works well with exceptions, where you can add the error message right from the exception:

nonstd::expected<int, std::string> queryDatabase() {
  try {
    return callIntoDatabase();
  } catch (const std::exception& exception) {
    return nonstd::make_unexpected(exception.what());
  }
}
..
auto record = queryDatabase();
if (!record) {
  std::cout << record.error() << std::endl;
}

Btw and out of topic, if you do code reviews in your team I’d like to invite you to this quick 3 minute, anonymous survey which helps understand the challenges people have when reviewing code. Thank you!