The assertion and the error codes are the two older ways of dealing with the failures, and they are still the right answer in a lot of places. The assertion checks the things that must be true, and the error code reports the things that are expected to fail. The exception is the third tool, and it is the most powerful and the most expensive.
The previous lesson in this module covered "What Is Exception Safety and When Is noexcept Right?", and the next lesson in this module is about "Which Patterns Validate Real-World Input?".
assert checks an invariant
The assertion is for checking the things that must be true, and not for handling the things that might not be.
#include <cassert>
#include <iostream>
int divide(int numerator, int denominator) {
assert(denominator != 0);
return numerator / denominator;
}
int main() {
std::cout << "10 / 2 = " << divide(10, 2) << '\n';
std::cout << "all checks passed\n";
return 0;
}The output shows the successful path.
10 / 2 = 5
all checks passedassert disappears in the release builds
When you compile with the NDEBUG flag, which the release builds usually do, the assertion macro expands to nothing at all.
#include <cassert>
#include <iostream>
int main() {
std::cout << "assert is enabled: " <<
#ifdef NDEBUG
false
#else
true
#endif
<< '\n';
assert(1 == 1); // a failing assertion aborts the program instead
std::cout << "still running\n";
return 0;
}And that is why you must never put the important work inside an assertion. If the check disappears in the release build then the work disappears with it, and the release build behaves differently from the debug build.
Error codes report expected failures
An error code in the return value is the fastest and the most predictable mechanism, and it costs nothing when it does not fire.
#include <iostream>
enum class PaymentStatus {
Approved,
Declined,
InsufficientFunds
};
PaymentStatus charge(int amount, int balance) {
if (amount <= 0) {
return PaymentStatus::Declined;
}
if (amount > balance) {
return PaymentStatus::InsufficientFunds;
}
return PaymentStatus::Approved;
}
int main() {
PaymentStatus status = charge(500, 100);
switch (status) {
case PaymentStatus::Approved:
std::cout << "approved\n";
break;
case PaymentStatus::Declined:
std::cout << "declined\n";
break;
case PaymentStatus::InsufficientFunds:
std::cout << "insufficient funds\n";
break;
}
return 0;
}The output shows the failure being reported without any exception machinery.
insufficient fundsstd::expected combines both
The newer standard library has the std::expected, which holds either a value or an error. The caller has to handle the error case to get the value, so the check is enforced by the compiler.
#include <iostream>
#include <string>
// A simplified stand-in for std::expected.
template <typename T>
class Result {
public:
static Result ok(const T& value) {
return Result(value, true, "");
}
static Result error(const std::string& message) {
return Result(T{}, false, message);
}
bool has_value() const { return holds_value_; }
const T& value() const { return data_; }
const std::string& message() const { return message_; }
private:
Result(const T& data, bool holds_value, const std::string& message)
: data_(data), holds_value_(holds_value), message_(message) {}
T data_;
bool holds_value_;
std::string message_;
};
Result<int> charge(int amount) {
if (amount <= 0) {
return Result<int>::error("amount must be positive");
}
return Result<int>::ok(amount * 100);
}
int main() {
Result<int> result = charge(250);
if (result.has_value()) {
std::cout << "charged " << result.value() << " cents\n";
} else {
std::cout << "failed\n";
}
return 0;
}The output shows the success path.
charged 25000 centsChoosing a strategy
the situation the tool
----------------------------------- ----------------------------------
it must be true and a failure is the assertion
a bug in the program
the failure is expected and it is an error code
ordinary
the failure is expected and it std::optional or std::expected
has to carry a message
the failure is a genuine bug or an exception
a rare external problem
A mixed approach
The real code uses all of them, in the places where each one fits.
#include <cassert>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
std::optional<int> lookup(const std::string& id) {
if (id == "p-001") {
return 100;
}
return std::nullopt;
}
int main() {
// An assertion for an invariant.
assert(lookup("p-001").has_value());
// An optional for a value that may not exist.
auto found = lookup("p-009");
if (!found.has_value()) {
std::cout << "not found, using a default\n";
}
// An exception for a genuine programming error.
try {
throw std::logic_error("the payment table is corrupt");
} catch (const std::logic_error& error) {
std::cout << "caught: " << error.what() << '\n';
}
return 0;
}The output shows each of the strategies doing its own job.
not found, using a default
caught: the payment table is corruptQuick reference
- The assertion checks the invariants and it disappears in the release builds.
- Never put the important work inside an assertion, because it disappears with it.
- The error codes are the fastest and the cheapest way to report the expected failures.
- The
std::expectedholds either a value or an error, and the compiler makes you check. - The
std::optionalholds a value or nothing, and it is the simplest of the two. - Use the exception for the rare failures, and never for the ordinary control flow.
Try it yourself: write a function that divides two numbers and that reports the failure with an error code, then rewrite it with an optional, and then with an exception. Time each of the three over a million calls and compare the results. Finally, put an assertion in the code and build it once with the debug flags and once with the release flags, and watch it disappear.