← Fundamentals
Fundamentals

Errors as values or exceptions

Follow the failure signal to the code that chooses the next action.

An operation’s API determines how a missing normal result reaches its caller.

Outcome

Say how a failure reaches the caller in each language, handle it where the next action is decided, keep a failure from being silently ignored, and tell different failures apart.

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.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#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';
    }
}
What does the program print?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#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';
}
What happens?

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().

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#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;
}
What happens on the second call?

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.

  1. easy · F-ERRREP-V4-1 Keep serving after a refusal
  2. medium · F-ERRREP-V4-2 Reject invalid quantity words
  3. hard · F-ERRREP-V4-3 Tell unknown items from empty ones
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.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.