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.
- Propagation
- Passing a failure from a callee to its caller, layer by layer, until something handles it.
- Unwinding
- Leaving active call scopes as an exception propagates toward a handler; applicable cleanup still runs.
- Context
- Information a layer adds to a failure, such as which hedge it was pricing.
- Cause
- The original failure kept inside a wrapping one, so callers can still inspect it.
- std::throw_with_nested
- The shown non-final runtime_error wrapper can carry the exception currently being handled as a nested cause.
Passing a failure through callers
Propagation passes a failed operation’s outcome through the calls that depend on it. Each layer must preserve enough information for the eventual handler. Context describes what that layer was attempting; a retained cause identifies the underlying failure independently of its displayed message.
A thrown exception unwinds intervening calls until a matching handler. Constructed automatic objects are destroyed as their scopes leave. A contextual exception can retain a nested exception; its message text and nested cause are separate information.
01On the way out
Which completion lines survive a failed price lookup?
A garden-planning tool quotes each hedge from its plant and length. An unlisted plant must leave a useful failure at the quote screen. The price lookup knows which plant is missing; the hedge layer knows which hedge was being priced. The report needs both pieces.
The quote screen must distinguish a completed hedge price from a call that never returned a price. The reduced plan requests box, then holly, and each successful hedge announces itself before the total. Trace the call that fails.
perMetre throws; hedge and plan have no try; main catches.
#include <iostream>
#include <stdexcept>
#include <string>
int perMetre(const std::string &plant) {
if (plant != "box") {
throw std::runtime_error("no price for " + plant);
}
return 4;
}
int hedge(const std::string &plant, int metres) {
int cost = perMetre(plant) * metres;
std::cout << "priced " << plant << '\n';
return cost;
}
void plan() {
int first = hedge("box", 3);
int second = hedge("holly", 2);
std::cout << "total " << first + second << '\n';
}
int main() {
try {
plan();
} catch (const std::exception &error) {
std::cout << "failed: " << error.what() << '\n';
}
}
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main
Use a fresh directory and replace main for each probe. For TypeScript, set package.json’s type field to commonjs while preserving its other fields, use the installed TypeScript and Node types, and run the guarded emit command shown. The Go and Rust commands use the supplied single main file. These examples make ordinary synchronous calls.
02Lost on the way
A middle layer that turns the failure into a value hides it from everyone above
A proposed fallback keeps the quote printable by treating an unlisted plant as cost 0. Try that change in the reduced two-hedge plan and inspect what the report can now distinguish.
hedge catches (...) and returns 0.
#include <iostream>
#include <stdexcept>
#include <string>
int perMetre(const std::string &plant) {
if (plant != "box") {
throw std::runtime_error("no price for " + plant);
}
return 4;
}
int hedge(const std::string &plant, int metres) {
try {
return perMetre(plant) * metres;
} catch (...) {
return 0;
}
}
int main() {
try {
int first = hedge("box", 3);
int second = hedge("holly", 2);
std::cout << "total " << first + second << '\n';
} catch (const std::exception &error) {
std::cout << "failed: " << error.what() << '\n';
}
}
03Context and cause
Does a contextual message still carry the original cause?
The report also needs the failing hedge’s name. This attempt puts “pricing north” and the old message into a new failure. The observer separately checks whether a typed UnknownPlant cause is still attached. Predict that check.
The catch builds a new runtime_error from text. The observer handles the case where rethrow_if_nested finds no nested exception.
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
struct UnknownPlant : std::runtime_error {
using std::runtime_error::runtime_error;
};
int perMetre(const std::string &plant) {
if (plant != "box") {
throw UnknownPlant("no price for " + plant);
}
return 4;
}
int hedge(const std::string &name, const std::string &plant, int metres) {
try {
return perMetre(plant) * metres;
} catch (const std::exception &error) {
throw std::runtime_error("pricing " + name + ": " + error.what());
}
}
int main() {
try {
hedge("north", "holly", 2);
} catch (const std::exception &error) {
std::cout << error.what() << '\n';
std::string causeMessage = "none";
bool unknownPlant = false;
try {
std::rethrow_if_nested(error);
} catch (const UnknownPlant &cause) {
causeMessage = cause.what();
unknownPlant = true;
}
std::cout << "cause: " << causeMessage << '\n';
std::cout << "unknown plant: " << (unknownPlant ? "true" : "false") << '\n';
}
}
04Repair the hedge planner
Let failures through, add context, handle the right one
The garden planner needs three focused repairs. Keep a missing price visible at the report, attach the current hedge’s name without losing its cause, then apply the box fallback only to an unknown plant. A bad length still belongs in the failure report.
Each ticket is a complete file with its supplied reader and caller. Repair the named pricing layer and check the report for each request.
Repair the hedge planner
Preserve a failure, attribute it to the current hedge, then choose which failure this layer can recover from.
Sign in to keep your read marks on every device. Sign in
Was this helpful?