Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Failure value
- A failure returned as an ordinary value, such as a Go error or a Rust Err, that the caller must check.
- Exception
- A raised failure that transfers ordinary control toward a matching handler; cleanup may run along that path.
- Swallowed failure
- A failure caught or received and then ignored, so the program carries on as if it had succeeded.
- std::expected
- A C++23 value that holds either a result or an error, the value family in C++.
- [[nodiscard]]
- An attribute discouraging discarded results; the C++ standard recommends a diagnostic.
How an operation reports failure
A failure representation carries the information a caller needs when an operation cannot produce its normal result. A returned failure travels through ordinary values; an exception transfers control to a matching handler. Handling means choosing the next action, such as refusing one request or stopping the current operation.
C++ APIs can throw exceptions or return a failure representation such as std::expected<T, E>. A handler catches a matching exception; a returned result requires inspection through its own API. Choose the reasoning model from the particular operation’s contract.
01Two ways to fail
Follow the shown API’s failure route
A clinic dispensary records kit requests. A shortage should identify the affected request without losing later work. Entered quantities can also fail conversion, and a missing item needs a different response from a known item that has run out. The tool must preserve those failure signals until the caller decides what to report.
A small kit starts with 3 units. Each treatment asks take for 2 units and reports completion afterward. Trace the calls for ana and ben, including which caller decides how to report a shortage.
take throws std::runtime_error; main catches std::exception.
#include <iostream>
#include <stdexcept>
#include <string>
struct Kit {
int left;
};
int take(Kit &kit, int count) {
if (count > kit.left) {
throw std::runtime_error("only " + std::to_string(kit.left) + " left");
}
kit.left -= count;
return kit.left;
}
void treat(Kit &kit, const std::string &patient) {
take(kit, 2);
std::cout << "treated " << patient << '\n';
}
int main() {
Kit kit{3};
try {
treat(kit, "ana");
treat(kit, "ben");
std::cout << "all treated\n";
} catch (const std::exception &error) {
std::cout << "failed: " << error.what() << '\n';
}
}
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main
Save one complete probe in a fresh directory under its selected filename. Use local TypeScript and Node types with the declared ES2022/Node16 CommonJS emit workflow; set package.json’s type field to commonjs, preserving other fields. Rust uses edition 2024. The C++ track uses the shown C++2c compiler profile. Each command is guarded so a failed build is not followed by a stale executable.
02The trap
Each way of reporting a failure has its own way of losing it
A caller requests 5 units from a kit of 3. Inspect what the following report does with the operation’s failure signal before predicting its line.
take returns a [[nodiscard]] bool; the call stands on its own line.
#include <iostream>
struct Kit {
int left;
};
[[nodiscard]] bool take(Kit &kit, int count) {
if (count > kit.left) {
return false;
}
kit.left -= count;
return true;
}
int main() {
Kit kit{3};
take(kit, 5);
std::cout << "gave 5, left " << kit.left << '\n';
}
03Converting
Observe a checked conversion from a failure value
The import path for quantity words will need to decide whether conversion failure is reportable data or a reason to stop. This reduced probe takes 2 units from 3, then asks for 2 from the remaining 1. Inspect the operation that extracts a value from each result.
take returns std::expected; the program calls value().
#include <expected>
#include <iostream>
#include <string>
std::expected<int, std::string> take(int left, int count) {
if (count > left) {
return std::unexpected("only " + std::to_string(left) + " left");
}
return left - count;
}
int main() {
std::cout << take(3, 2).value() << std::endl;
std::cout << take(1, 2).value() << std::endl;
}
04Repair the dispensary
Keep serving, reject bad quantities, tell failures apart
The dispensary needs to keep processing after a refused request, report failed quantity conversions and distinguish an absent item from exhausted stock. Each supplied complete file carries the relevant reader and working support operations.
Repair the dispensary
Continue the request list, preserve conversion failures and reconcile two expected stock failures.
In the frontend Keep failure status beside its display data. Optional
A component can receive an operation’s outcome as a value. Zero remaining units can be a successful result; a failure carries a message. Render using the explicit status so the display does not turn a failure into a plausible numeric default.
type Outcome =
| { ok: true; remaining: number }
| { ok: false; message: string };
export default function KitOutcome({ outcome }: { outcome: Outcome }) {
return outcome.ok
? <p>{outcome.remaining} units left</p>
: <p role="status">{outcome.message}</p>;
}
The component receives the result; it does not catch a throwing operation. An ok result with remaining 0 renders 0 units left, while a failed result renders its message.
Sources: React conditional rendering,Svelte if blocks,Svelte props.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?