Errors and failure contracts
What you will learn on this page
Section titled “What you will learn on this page”- What a failure contract is, and why every function that can fail needs one.
- How to tell a caller’s mistake (a broken precondition) from an expected failure, such as bad input from a user.
- When to report failure with an exception, and when with an error value:
std::optionalorstd::variant. - What
noexceptpromises, and when to write it.
Every function that can fail has a failure contract
Section titled “Every function that can fail has a failure contract”A function’s normal contract says what it needs and what it gives back:
parse_member_id("M-1042") returns member 1042. Its failure contract says
what happens when it cannot do that:
- Which failures can happen? Empty text, a missing
"M-", letters in the number, a number out of range. - How is each one reported? A thrown exception, a returned error value, or not at all, because it is a bug in the caller.
- What state is left behind? Is everything as it was, or partly changed?
- What must the caller do? Check a result, catch an exception, or simply never pass that input.
If the failure contract is not designed, it still exists. It is just accidental: whatever the code happens to do, which callers then depend on.
Three kinds of failure
Section titled “Three kinds of failure”Not all failures are alike, and the kind decides the reporting style.
- Expected failures. Bad input is a normal event: a member types
m-1042at a self-service kiosk. The caller is ready to handle it, right where it calls. These are best reported as error values, which are hard for the caller to ignore by accident. - Unexpected failures. Something that should not happen, but can: a saved file that was valid yesterday contains a corrupt ID, a disk is full, memory runs out. The code that notices cannot fix it, and the code that can (often far up the call stack) needs to know. These are best reported as exceptions.
- Bugs: broken preconditions. A precondition is something the caller
must make true before calling. If
MemberId(int)requires a number from 1 to 999999 and a caller passes 0, the caller is wrong, and no error message to the member can fix the code. Reporting it loudly, and fixing the caller, is the only real cure.
The example: a member ID with an invariant
Section titled “The example: a member ID with an invariant”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A library member's ID, such as M-1042. It is a small value: copy it freely.// Invariant: 1 <= number() <= 999999. The constructor is the only way to// make one from a number, and it refuses any other number, so every MemberId// that exists is valid and no function that receives one has to check again.// The `= default` operator== below asks the compiler to write ==: two IDs// are equal when their numbers are equal. `friend` lets it be written inside// the class and still be called as a plain a == b.class MemberId {public: // The largest allowed number, shared by the class and its users (static) // and fixed at compile time (constexpr). The ' is only a digit separator, // like a comma in 999,999; the value is 999999. static constexpr int max_number = 999'999;
// Precondition: 1 <= number <= max_number. Breaking it is a bug in the // caller, so it throws std::out_of_range rather than returning an error. explicit MemberId(int number);
[[nodiscard]] int number() const noexcept { return number_; } [[nodiscard]] std::string text() const; // "M-" followed by the number friend bool operator==(const MemberId&, const MemberId&) = default;
private: int number_;};MemberId has an invariant: its
number is always from 1 to 999999. Once a MemberId exists, every function that
receives one can rely on it without checking again. The constructor enforces the
invariant, so the constructor’s precondition is the same range. Breaking it
throws std::out_of_range, which says “a caller has a bug” rather than “the
member typed something wrong”.
Strictly, a precondition says what happens only when it is kept: if it is
broken, the function promises nothing. Many functions in the standard library
work this way; operator[] on a vector with a bad index simply has undefined
behaviour. This example chooses to check its precondition and throw, so that
a bug shows up at once, in a test, as a clear failure. Other code bases use
assert, which checks only in debug builds. Either way, the check is a safety
net for finding bugs, not a way of reporting failure: no caller should rely on
it, or catch std::out_of_range here to recover. The fix is always in the
caller.
The interesting question is how to turn text into a MemberId, because text
from outside can be anything. The example offers both styles, so they can be
compared.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every way that text can fail to be a member ID, with examples:// empty ""// missing_prefix does not start with "M-": "1042", "m-1042"// not_a_number nothing, a sign, or junk after "M-": "M-", "M--5", "M-12x"// out_of_range a number, but not 1 to 999999: "M-0", "M-1000000"// `enum class` names a fixed set of values. Unlike a plain enum, each name is// written with the type in front (ParseError::empty), and it does not turn// into an int by itself, so a reason cannot be mixed up with a number.enum class ParseError { empty, missing_prefix, not_a_number, out_of_range };
// A short English sentence for a reason, such as "the text is empty", for// messages shown to people. The string_view looks at a string literal, which// lives for the whole program, so it never dangles. noexcept: it only picks// one of a few fixed texts, so it cannot fail.[[nodiscard]] std::string_view describe(ParseError error) noexcept;An enum class lists every way the text can fail. It is part of the failure
contract: a caller can tell missing_prefix from out_of_range and react
differently, for example by showing a different hint.
Style 1: error values
Section titled “Style 1: error values”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Error-value style. Neither function throws: failure is a normal result// that the caller must look at.
// Either a MemberId or the reason the text is not one.// std::variant<MemberId, ParseError> always holds exactly one of the two// and remembers which. The caller asks which (for example with// std::get_if) before using the value.using ParseResult = std::variant<MemberId, ParseError>;// Reads text such as "M-1042": a MemberId if the text is valid, otherwise// the first problem found. It reads `text` only during the call.// [[nodiscard]]: the compiler warns if a caller ignores the result.// noexcept: every failure is returned as a value, never thrown.[[nodiscard]] ParseResult parse_member_id(std::string_view text) noexcept;
// When the caller only needs to know whether it worked.// Returns the MemberId, or an empty optional (std::nullopt) if the text is// not valid; the reason is dropped. It calls parse_member_id, so the two// always agree about which texts are valid.[[nodiscard]] std::optional<MemberId> try_parse_member_id(std::string_view text) noexcept;ParseResult is a std::variant<MemberId, ParseError>: an object that holds
exactly one of the two, a valid ID or the reason there is none. The result
type itself tells the caller that the call can fail, and [[nodiscard]] makes
the compiler warn if the caller ignores it.
std::optional<MemberId> is the simpler form when the caller only needs “it
worked, here is the ID” or “it did not”. It holds a MemberId or nothing, and
throws away the reason.
Error values have costs. Every caller must check, and a caller that cannot handle the failure has to pass it up by hand, through every function between the failure and the code that can deal with it.
Style 2: exceptions
Section titled “Style 2: exceptions”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Exception style. Thrown by member_id_from(); carries the reason.// It derives from the standard std::invalid_argument, so a handler that// catches std::invalid_argument or std::exception catches it too, and// what() gives a whole message, such as:// invalid member ID "M-0": the number is not between 1 and 999999// reason() gives the same ParseError that parse_member_id would return.class InvalidMemberId : public std::invalid_argument {public: // Builds the what() message from the text and the reason. The text is // copied into the message, so the exception stays valid after the // caller's characters are gone. InvalidMemberId(std::string_view text, ParseError reason); [[nodiscard]] ParseError reason() const noexcept { return reason_; }
private: ParseError reason_;};
// Postcondition: returns a valid MemberId. Throws InvalidMemberId otherwise.// For text that should always be valid, such as saved data: the caller can// use the result at once, and a failure goes to a catch further up.[[nodiscard]] MemberId member_id_from(std::string_view text);member_id_from returns a plain MemberId, so a caller that gets a result can
use it straight away. On failure it throws an InvalidMemberId. It derives
from the standard std::invalid_argument, so a general handler that catches
std::exception still sees a readable message through what(), and a specific
handler can ask for reason().
When an exception is thrown, the functions between the throw and the matching
catch are left immediately, and their local objects are destroyed on the way
(which is why RAII matters). The code in
between does not need to check anything, which is the main reason to choose
exceptions: failures that the nearby code cannot handle travel to code that can,
without cluttering every function on the way.
The comment on member_id_from states its postcondition: what is true when
it returns normally. Here, it returns a valid MemberId; otherwise, it does not
return at all, but throws.
One parser behind both styles
Section titled “One parser behind both styles”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The one real parser. Each check returns the first problem it finds, in// order, so the code after a check only runs for text that passed it. Every// return is either a ParseError or a MemberId; both convert to ParseResult.ParseResult parse_member_id(std::string_view text) noexcept { if (text.empty()) return ParseError::empty; constexpr std::string_view prefix = "M-"; // The first two characters must be exactly "M-". substr gives fewer // characters if the text is shorter ("M" alone), which cannot match. if (text.substr(0, prefix.size()) != prefix) return ParseError::missing_prefix;
// The rest, after "M-": "1042" for "M-1042". It may be empty ("M-"). const std::string_view digits = text.substr(prefix.size()); // Pointers to the first character and to one past the last: the range // std::from_chars reads. const char* const first = digits.data(); const char* const last = digits.data() + digits.size(); int number = 0; // Reads an int from the start of the range into `number`. It never // throws; it returns where it stopped (`end`) and a std::errc (`error`), // unpacked here into two names by a structured binding. std::errc{} means // success; result_out_of_range means the digits were too big for an int. const auto [end, error] = std::from_chars(first, last, number); // Rule out signs before looking at `error`: "M--5" would otherwise be // read as the number -5 and reported as out_of_range, not not_a_number. if (digits.empty() || digits.front() == '-' || digits.front() == '+') { return ParseError::not_a_number; // from_chars accepts a leading '-' } if (error == std::errc::result_out_of_range) return ParseError::out_of_range; // Any other error (no digits at the start), or digits followed by // something else ("M-12x", "M-12 "), so reading stopped before `last`. if (error != std::errc{} || end != last) return ParseError::not_a_number; // A clean int, but it must also fit the MemberId range: "M-0" and // "M-1000000" are numbers, just not member numbers. if (number < 1 || number > MemberId::max_number) return ParseError::out_of_range;
return MemberId(number); // cannot throw: the precondition was just checked}
// The optional style, built on the parser so the two cannot disagree.// std::get_if<MemberId>(&result) returns a pointer to the MemberId inside// the variant if that is what it holds, and nullptr otherwise. The pointer is// declared inside the `if`, so the branch runs only when it is not null.std::optional<MemberId> try_parse_member_id(std::string_view text) noexcept { ParseResult result = parse_member_id(text); if (const MemberId* id = std::get_if<MemberId>(&result)) return *id; // copy the ID out return std::nullopt; // the variant held a ParseError: report "no ID"}
// The part after `:` passes the finished message to the base class,// std::invalid_argument, which stores it for what(). std::string(text) and// std::string(describe(reason)) turn the string_views into strings, because// a string_view cannot be joined with + to text in quotes.InvalidMemberId::InvalidMemberId(std::string_view text, ParseError reason) : std::invalid_argument("invalid member ID \"" + std::string(text) + "\": " + std::string(describe(reason))), reason_(reason) {}
// The exception style, also built on the parser. If the variant holds a// ParseError, throw it inside an InvalidMemberId. Otherwise it must hold a// MemberId, so std::get<MemberId> is safe (std::get throws// std::bad_variant_access only when asked for the type that is not held).MemberId member_id_from(std::string_view text) { ParseResult result = parse_member_id(text); if (const ParseError* error = std::get_if<ParseError>(&result)) { throw InvalidMemberId(text, *error); } return std::get<MemberId>(result);}How this code works: parse_member_id
parse_member_id is a ladder of checks. Each one either returns a
ParseError at once or lets the text through to the next. Only text that
passes every check reaches the last line and becomes a MemberId.
- Empty?
""stops here asempty. - Prefix. The first two characters must be
M-."1042","X-1", and"m-1042"stop here asmissing_prefix. - Split off the digits.
digitsis everything afterM-, andfirstandlastpoint at its start and one past its end. - Read a number.
std::from_charsreads as many digits as it can from the start, stores the value innumberif it succeeds, and reports where it stopped (end) and whether it failed (error). It runs before the sign check, but its result is not looked at until after it. - Signs and nothing. No digits at all, or a leading
-or+, isnot_a_number. This check comes before the error checks on purpose:from_charswould read"-5"as the number -5, which the range check would then callout_of_range. - Too big for an
int.result_out_of_rangebecomesout_of_range. - Junk. Any other error, or reading that stopped before
last(something after the digits), isnot_a_number. - Range. A clean number outside 1 to 999999 is
out_of_range. - Success.
MemberId(number)cannot throw now, so thenoexceptpromise holds.
Some inputs from the example and the tests, traced:
| Text | digits |
What from_chars reports |
Stops at step | Result |
|---|---|---|---|---|
"M-1042" |
"1042" |
1042, no error, stopped at the end | 9 | MemberId(1042) |
"M-" |
"" |
an error: nothing to read | 5 | not_a_number |
"M--5" |
"-5" |
-5, no error, stopped at the end | 5 | not_a_number |
"M-99999999999" |
"99999999999" |
result_out_of_range |
6 | out_of_range |
"M-12x" |
"12x" |
12, no error, stopped before x |
7 | not_a_number |
"M-0" |
"0" |
0, no error, stopped at the end | 8 | out_of_range |
The two wrappers only translate. try_parse_member_id asks the variant
“do you hold a MemberId?” with std::get_if, and copies it into an
optional if so. member_id_from asks “do you hold a ParseError?” and, if
so, throws it inside an InvalidMemberId; if not, the variant must hold a
MemberId, which it returns.
The parsing logic exists once, in parse_member_id. try_parse_member_id and
member_id_from only convert its result to the other styles, so the three can
never disagree about what is valid. Notice the details the failure contract
forced: std::from_chars accepts a leading - (though not a +), so the
parser rejects both signs itself, as one clear rule, and a number too big for an int is reported as out_of_range, not as
a crash or a wrapped-around value.
The last line calls MemberId(number), whose constructor can throw, inside a
noexcept function. That is safe only because every input that would break the
precondition has already been rejected. The comment says so, and the tests check
the boundary values.
Using each style where it fits
Section titled “Using each style where it fits”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Error values: typed input, where a bad value is expected and handled// right here.// Four inputs: one valid, then a lowercase prefix, junk after the digits,// and a number outside the range.constexpr std::array<std::string_view, 4> typed{"M-1042", "m-1042", "M-12x", "M-0"};for (const std::string_view text : typed) { const auto result = parse_member_id(text); // Is it a MemberId? get_if gives a pointer to it, or nullptr if the // variant holds a ParseError instead. if (const auto* id = std::get_if<MemberId>(&result)) { std::cout << text << ": member " << id->number() << '\n'; } else { // Not a MemberId, so it must be a ParseError: std::get is safe. std::cout << text << ": rejected, " << describe(std::get<ParseError>(result)) << '\n'; }}
// Exceptions: data that should always be valid, such as a saved file.// A bad ID is unexpected, so one handler further up deals with it.// The third ID is too big: member_id_from throws before its "loaded" line// is printed, the loop is abandoned, and control jumps to the catch below.try { for (const std::string_view saved : {"M-7", "M-19", "M-1000000"}) { const MemberId id = member_id_from(saved); // parse before printing std::cout << "loaded " << id.text() << '\n'; }} catch (const InvalidMemberId& error) { // Caught by const reference: no copy, and no slicing. what() is the // message InvalidMemberId built from the text and the reason. std::cout << "loading stopped: " << error.what() << '\n';}M-1042: member 1042m-1042: rejected, it does not start with "M-"M-12x: rejected, the part after "M-" is not a numberM-0: rejected, the number is not between 1 and 999999loaded M-7loaded M-19loading stopped: invalid member ID "M-1000000": the number is not between 1 and 999999The typed IDs use error values: a bad one is expected, and the loop handles it right there, then moves on to the next. The saved IDs use exceptions: a bad one means the saved data is corrupt, so loading stops, and one handler outside the loop reports it.
That last point is the third question of a failure contract, “what state is left behind?”. Exception safety and failure atomicity treats it in depth. In short, a function gives the basic guarantee if a failure leaves everything valid but possibly changed, the strong guarantee if a failure leaves everything as it was, and the no-throw guarantee if it never fails.
The failure paths at a glance
Section titled “The failure paths at a glance”Text description of the diagram
Text from outside goes to parse_member_id. Valid text produces a MemberId.
Invalid text produces a ParseError value with one of four reasons. What
happens next depends on which function the caller called; all three use the
same parser: with parse_member_id
the caller handles the reason on the spot; with try_parse_member_id it gets an
empty std::optional and the reason is dropped; with member_id_from an
InvalidMemberId exception is thrown and caught by a handler further up the
call stack. Separately, code that builds a MemberId directly from an int
must pass 1 to 999999. Any other number breaks the constructor’s precondition,
and the constructor throws std::out_of_range, which signals a bug to fix in
the calling code.
Diagram source (Mermaid)
flowchart TD
T["text from outside"] --> P{"parse_member_id"}
P -->|valid| ID["MemberId"]
P -->|"empty, missing_prefix, not_a_number, out_of_range"| E["ParseError value"]
E --> Q{"which function was called? All three share this parser"}
Q -->|"parse_member_id"| V["caller handles the reason right here"]
Q -->|"try_parse_member_id"| O["empty optional; the reason is dropped"]
Q -->|"member_id_from"| X["throws InvalidMemberId"]
X --> C["a catch further up the call stack"]
N["int chosen by code"] --> K{"MemberId constructor"}
K -->|"1 to 999999"| ID
K -->|"anything else: precondition broken"| B["throws std::out_of_range: fix the caller"]noexcept: a promise not to throw
Section titled “noexcept: a promise not to throw”noexcept on a function is a promise that it never lets an exception escape. If
one tries, the program does not continue: std::terminate is called, which
normally ends the program. The promise therefore has to be true for every
input.
parse_member_idandtry_parse_member_idarenoexcept. They allocate nothing and report every failure as a value, so the promise holds.member_id_fromis not, because throwing is how it reports failure.describeand the small accessors arenoexcept: they cannot fail.
Why write it? Callers, and the standard library, can rely on it. The most
important case is the move constructor: std::vector only moves elements when it
grows if the move constructor is noexcept (or the type cannot be copied), as the
copy-and-move lesson showed. Destructors are noexcept by default.
Add noexcept only if you can keep the promise for every input, including when
memory runs out. If the function calls code that might throw, either handle that
inside it or leave noexcept off, and think about whether it might be changed
later to do so. Removing a noexcept later can break callers that relied on it.
Testing the failure contract
Section titled “Testing the failure contract”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, LLD_CHECK_EQ(actual, expected) records one,// printing both values, unless they are equal, and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws that// type of exception. They come from the site's small test header,// lld_test.hpp. error_for(text), a helper defined above this snippet,// returns the ParseError that parse_member_id gives for `text`.//// The last two tests: both_styles_agree runs six inputs through the optional// style and the exception style. For a valid text, member_id_from returns an// ID equal to the optional's. For an invalid one it throws before the// comparison inside LLD_CHECK happens, so the catch block runs instead and// checks that the optional is empty and that the exception carries the same// reason as parse_member_id. broken_precondition_throws calls the// constructor with numbers just outside 1..999999: that is a bug in the// caller, reported as std::out_of_range, not as an InvalidMemberId.
// noexcept(expression) asks the compiler "can this expression throw?"// without running it; static_assert stops the build if the answer is wrong.static_assert(noexcept(parse_member_id("M-1")));static_assert(noexcept(try_parse_member_id("M-1")));static_assert(!noexcept(member_id_from("M-1")));
// One input or more for every ParseError, including the tricky ones: a// second minus sign, a plus sign, a trailing space, and an 11-digit number.LLD_TEST(each_failure_has_its_reason) { LLD_CHECK(error_for("") == ParseError::empty); LLD_CHECK(error_for("1042") == ParseError::missing_prefix); LLD_CHECK(error_for("M-") == ParseError::not_a_number); LLD_CHECK(error_for("M--5") == ParseError::not_a_number); LLD_CHECK(error_for("M-+5") == ParseError::not_a_number); LLD_CHECK(error_for("M-12 ") == ParseError::not_a_number); LLD_CHECK(error_for("M-99999999999") == ParseError::out_of_range); // overflows int}
// The values just outside (0, 1000000) and just inside (1, 999999) the// valid range. try_parse_member_id returns an optional, and comparing it// with a MemberId is true only if it holds an equal ID.LLD_TEST(range_boundaries) { LLD_CHECK(error_for("M-0") == ParseError::out_of_range); LLD_CHECK(try_parse_member_id("M-1") == MemberId(1)); LLD_CHECK(try_parse_member_id("M-999999") == MemberId(999'999)); LLD_CHECK(error_for("M-1000000") == ParseError::out_of_range);}
LLD_TEST(both_styles_agree) { constexpr std::array<std::string_view, 6> inputs{"M-1", "M-42", "", "X-1", "M-4x", "M-0"}; for (const std::string_view text : inputs) { const std::optional<MemberId> value = try_parse_member_id(text); try { LLD_CHECK(value == member_id_from(text)); } catch (const InvalidMemberId& error) { LLD_CHECK(!value.has_value()); LLD_CHECK(error.reason() == std::get<ParseError>(parse_member_id(text))); } }}
LLD_TEST(broken_precondition_throws) { LLD_CHECK_THROWS(MemberId(0), std::out_of_range); LLD_CHECK_THROWS(MemberId(1'000'000), std::out_of_range); LLD_CHECK_EQ(MemberId(1042).text(), std::string("M-1042"));}The failure contract is behaviour, so it is tested like the rest:
- The
static_assertlines check thenoexceptpromises at compile time, so removing one by accident fails the build. - Every
ParseErrorreason has at least one input that produces it, including the tricky ones (M--5, a trailing space, a number that overflows anint). - The range boundaries 0, 1, 999999 and 1000000 are all tested: the values just inside and just outside the limits are where mistakes hide.
- The two styles are checked against each other, and the constructor’s precondition is checked to throw.
Choosing a style
Section titled “Choosing a style”| Situation | Report it as |
|---|---|
| Bad input is common and the caller handles it on the spot | An error value: std::variant with a reason, or std::optional |
| The caller only needs to know whether it worked | std::optional |
| Failure is rare, and only code far up the call stack can deal with it | An exception |
| A constructor cannot establish its object’s invariant | Usually an exception (a constructor has no return value), or a factory function returning an error value |
| The caller broke a precondition | A loud failure (exception, assertion), and fix the caller |
| The code must not throw (destructors, move operations, some hot paths) | An error value, or handle the failure inside |
Teams and code bases also have rules of their own. Some disable exceptions entirely, for example in some embedded and game code; then error values are the only choice. Follow the code base’s rule, and keep each API consistent with it.
Common mistakes
Section titled “Common mistakes”- Returning a magic value, such as
-1or an empty string, for failure. The caller can forget to check, and the magic value may one day be valid. Make the failure visible in the type. - Using exceptions for normal control flow, such as throwing for every typo in a form that is checked keystroke by keystroke. If failure is the common case, return a value.
- Catching everything and carrying on, with
catch (...) {}. The failure is hidden, and the program continues in a state nobody designed. - Starting a visible effect before the step that can fail, as in the partial output above.
- A
noexceptthat is not true for every input. The result is not an error message but a terminated program. - Leaving the failure contract undocumented. The header comment should say what each function needs, what it returns, and how it fails.
When a requirement changes
Section titled “When a requirement changes”New requirement: “When a member mistypes an ID at the kiosk, show a hint that depends on the mistake.”
The error-value style already supports it: the caller gets a ParseError and
can choose a hint for each reason. If the API had only offered
try_parse_member_id, the reason would be gone, and the API would need to
change. That is why the parser returns the full reason and the simpler styles
are built on top: dropping information is easy for a caller, and recovering it
is impossible.
Second requirement: “Saved files from an old version used lowercase m-; load
them too.” This changes which inputs are valid, which is the normal
contract, not the failure contract. It belongs in one place, the parser, and the
tests for missing_prefix must change with it: a reminder that a failure
contract is part of an API and changes need the same care.
Exercise: Write a failure contract for renew_loan
A library service has this function:
// Renews the loan, extending its due date by 21 days.Loan renew_loan(LoanId id);A loan cannot be renewed if it does not exist, if it has already been renewed twice, or if another member has placed a hold on the book. The loan store is a database that can occasionally be unreachable.
- List the failures, and classify each as expected, unexpected, or a bug.
- Choose how each is reported, and write the new declaration.
- Say what state is left behind on each failure.
- Decide whether the function can be
noexcept.
Show the explained answer
-
Failures. Already renewed twice and on hold are expected: members try this every day, and the caller (the renewal screen) will show a message. Loan does not exist depends on where the ID came from: typed by a member, it is expected; taken from the member’s own loan list a moment ago, it means a bug or a race with another change. Database unreachable is unexpected: the renewal screen cannot fix it.
-
Reporting. The expected failures become values:
enum class RenewalRefused { no_such_loan, renewal_limit_reached, on_hold };using RenewalResult = std::variant<Loan, RenewalRefused>;// Precondition: none; every LoanId value is accepted.// Returns the renewed loan, or why it was refused.// Throws StoreUnavailable if the loan store cannot be reached.[[nodiscard]] RenewalResult renew_loan(LoanId id);The unreachable database stays an exception: it is rare, every function between here and the top of the request would otherwise have to pass it on, and one handler at the top can show “try again later”. Treating
no_such_loanas a value is the safer choice when IDs can come from members; if they never do, it could instead be a precondition. -
State. A refusal changes nothing: the loan keeps its due date and renewal count. On
StoreUnavailable, the contract should promise the same (the strong guarantee), which in practice means the change must be made in one database transaction, so it is either fully saved or not saved at all. -
noexcept? No. It can throwStoreUnavailable, and talking to a database may also allocate memory. Anoexcepthere would turn a temporary database problem into a terminated program.
Summary
Section titled “Summary”- Every function that can fail has a failure contract: which failures, how each is reported, what state is left, and what the caller must do. Design it on purpose.
- Report expected failures as values (
std::variantwith a reason, orstd::optional), unexpected ones as exceptions, and treat a broken precondition as a bug in the caller. - A constructor that cannot establish its invariant usually throws, because it
has no return value. Where exceptions are not used, a factory function that
returns
std::optionalorstd::variantdoes the job instead. noexceptis a promise for every input; if broken, the program terminates.- Finish the work that can fail before starting visible effects.