Skip to content

Absence and Invalid Requests

The Course
•
35 min study

An optional lookup answers one question: does task 9 exist? That is enough for a lookup, because there is only one way to fail. An edit is different. "Set task 9 to 0 minutes" can fail because there is no task 9, or because 0 is not a valid duration, and a later version may add "the tracker is full" or "that ID is already taken". If the edit returns only false, the program can say nothing better than "edit failed", and the user cannot tell whether to fix the ID or the number.

The fix is to name the outcomes. An enum class Error { none, missing, invalid }; gives each reason its own value, and the function returns the one that applies. The caller can then choose a precise message, count rejections by kind, or test that a specific mistake produces a specific error.

Predict and run

lookup knows only task 2. What does it print for 9?

Predict before running C++
#include <iostream>
#include <optional>

std::optional<int> lookup(int id) {
    if (id == 2) { return 25; }
    return std::nullopt;
}

int main() {
    auto result = lookup(9);
    std::cout << result.has_value() << "\n";
    return 0;
}
Check your prediction
Text
0

An empty optional is the honest answer for a missing task. Returning a made-up duration such as 0 instead would look like data: a report would add it, and a caller could not distinguish "task 9 takes 0 minutes" from "there is no task 9". Absence is a state, so the type should have room for it.

Name each reason to refuse

You wrote this kind of function in Day 2's checkpoint: find, then validate, then assign, with existence checked first so a missing task is reported as missing (that lesson explains why). Here it returns a named reason instead of false. What is new today is what the caller can do with that name, and how to stop a caller from ignoring it.

One function, three outcomes C++
#include <iostream>
#include <map>

enum class Error { none, missing, invalid };

Error set_minutes(std::map<int, int>& tasks, int id, int minutes) {
    auto found = tasks.find(id);
    if (found == tasks.end()) { return Error::missing; }
    if (minutes < 1 || minutes > 180) { return Error::invalid; }
    found->second = minutes;
    return Error::none;
}

const char* message(Error error) {
    switch (error) {
    case Error::none: return "ok";
    case Error::missing: return "no such task";
    case Error::invalid: return "minutes must be 1-180";
    }
    return "unknown error";
}

int main() {
    std::map<int, int> tasks{{2, 25}};
    std::cout << "2 -> 40: " << message(set_minutes(tasks, 2, 40)) << "\n";
    std::cout << "2 -> 0: " << message(set_minutes(tasks, 2, 0)) << "\n";
    std::cout << "9 -> 0: " << message(set_minutes(tasks, 9, 0)) << "\n";
    std::cout << "task 2 now " << tasks.find(2)->second << "\n";
    return 0;
}
Text
2 -> 40: ok
2 -> 0: minutes must be 1-180
9 -> 0: no such task
task 2 now 40

Error::none stands for success, so every call returns a value of the same type and the caller handles all outcomes in one place. Notice that the library function returns an Error and does no printing; main decides what the words are.

Errors without exceptions

Many C++ libraries report failures by throwing exceptions. This course does not, for two reasons. The browser compiler used here cannot build code with exceptions, and an explicit return value keeps failure visible in the function's signature: a reader of Error set_minutes(...) knows at a glance that it can fail and how.

The weakness of return values is that a caller can ignore them. This program asks to change task 9, ignores the answer, and reports success. Run it.

Fix the ignored result C++
#include <iostream>
#include <map>

enum class Error { none, missing, invalid };

[[nodiscard]] Error set_minutes(std::map<int, int>& tasks, int id, int minutes) {
    auto found = tasks.find(id);
    if (found == tasks.end()) { return Error::missing; }
    if (minutes < 1 || minutes > 180) { return Error::invalid; }
    found->second = minutes;
    return Error::none;
}

int main() {
    std::map<int, int> tasks{{2, 25}};
    set_minutes(tasks, 9, 30);
    std::cout << "Saved task 9\n";
    return 0;
}

The program prints Saved task 9, which is false: there is no task 9, and nothing was saved. Above the output, the compiler has a complaint:

Shell
main.cpp:16:5: warning: ignoring return value of function declared with 'nodiscard' attribute [-Wunused-result]

[[nodiscard]] in front of set_minutes asks the compiler to object when a call's result is thrown away. In the browser editor it is a warning: you see it, and the program still runs. The course's checker and a local build with -Werror (as on Day 7) turn every warning into an error, so there the program does not build at all:

Shell
main.cpp:16:5: error: ignoring return value of function declared with 'nodiscard' attribute [-Werror,-Wunused-result]

Fix the caller so it only claims success when set_minutes reports Error::none, and otherwise says what happened.

Check your fix

Use the result in a condition:

C++
#include <iostream>
#include <map>

enum class Error { none, missing, invalid };

[[nodiscard]] Error set_minutes(std::map<int, int>& tasks, int id, int minutes) {
    auto found = tasks.find(id);
    if (found == tasks.end()) { return Error::missing; }
    if (minutes < 1 || minutes > 180) { return Error::invalid; }
    found->second = minutes;
    return Error::none;
}

int main() {
    std::map<int, int> tasks{{2, 25}};
    if (set_minutes(tasks, 9, 30) == Error::none) {
        std::cout << "Saved task 9\n";
    } else {
        std::cout << "Not saved: no task 9\n";
    }
    return 0;
}
Text
Not saved: no task 9

Put [[nodiscard]] in front of functions whose result reports success or failure. When ignoring the result really is intended, write (void)set_minutes(tasks, 9, 30); so the choice is visible to readers and to the compiler.

One limit is worth stating plainly. These error values cover ordinary invalid input, which a program reading files must expect. Running out of memory is a different kind of failure: it is outside what this course promises to recover from, and turning exceptions off does not make it recoverable.

Keep diagnostics out of the library

A library function that prints its own error messages is hard to reuse and hard to test. The messages mix with normal output, the wording cannot change per application, and a test can only check text instead of a value. Return the Error, and let the application choose the message and the stream. The tracker's main counts rejected lines and writes only the report to standard output; a real tool would write diagnostics to std::cerr, which keeps them out of the report.

Practice

Exercise

Your turn

Named errors let a caller summarize a whole batch. Using the set_minutes from the fix step, write Tally apply_all(std::map<int, int>& tasks, const std::vector<Request>& requests), where struct Request { int id; int minutes; }; and Tally counts how many requests were applied, how many named a missing task and how many had invalid minutes. apply_all prints nothing; main prints the tally and then the map. For tasks {2, 25} and {7, 10} and the requests {2, 40}, {9, 30}, {7, 0}, {7, 15}, {4, 200}, print:

Text
applied: 2
missing: 2
invalid: 1
2: 40
7: 15
Your workspace C++
#include <iostream>
#include <map>
#include <vector>

enum class Error { none, missing, invalid };

[[nodiscard]] Error set_minutes(std::map<int, int>& tasks, int id, int minutes) {
    auto found = tasks.find(id);
    if (found == tasks.end()) { return Error::missing; }
    if (minutes < 1 || minutes > 180) { return Error::invalid; }
    found->second = minutes;
    return Error::none;
}

struct Request { int id; int minutes; };

// Write Tally and apply_all here.

int main() {
    std::map<int, int> tasks{{2, 25}, {7, 10}};
    const std::vector<Request> requests{{2, 40}, {9, 30}, {7, 0}, {7, 15}, {4, 200}};
    return 0;
}
Hint 1: the idea

Each call returns exactly one of three names, so each request adds one to exactly one counter. The [[nodiscard]] on set_minutes means the loop must use every result, which is exactly what a tally does. {4, 200} has two problems; the function's order of checks decides which counter it lands in.

Hint 2: a first step

Define Tally with three int counters that default to 0, and write apply_all so it loops over the requests and only counts Error::none results. Print the tally: you should see applied: 2 with the other two still 0. Then decide how to count the other two names in the same statement.

Show one solution
Run the solution C++
#include <iostream>
#include <map>
#include <vector>

enum class Error { none, missing, invalid };

[[nodiscard]] Error set_minutes(std::map<int, int>& tasks, int id, int minutes) {
    auto found = tasks.find(id);
    if (found == tasks.end()) { return Error::missing; }
    if (minutes < 1 || minutes > 180) { return Error::invalid; }
    found->second = minutes;
    return Error::none;
}

struct Request { int id; int minutes; };
struct Tally { int applied = 0; int missing = 0; int invalid = 0; };

Tally apply_all(std::map<int, int>& tasks, const std::vector<Request>& requests) {
    Tally tally;
    for (const Request& request : requests) {
        switch (set_minutes(tasks, request.id, request.minutes)) {
        case Error::none: ++tally.applied; break;
        case Error::missing: ++tally.missing; break;
        case Error::invalid: ++tally.invalid; break;
        }
    }
    return tally;
}

int main() {
    std::map<int, int> tasks{{2, 25}, {7, 10}};
    const std::vector<Request> requests{{2, 40}, {9, 30}, {7, 0}, {7, 15}, {4, 200}};
    const Tally tally = apply_all(tasks, requests);
    std::cout << "applied: " << tally.applied << "\n";
    std::cout << "missing: " << tally.missing << "\n";
    std::cout << "invalid: " << tally.invalid << "\n";
    for (const auto& [id, minutes] : tasks) {
        std::cout << id << ": " << minutes << "\n";
    }
    return 0;
}
Text
applied: 2
missing: 2
invalid: 1
2: 40
7: 15

A switch over the result handles each name once, and with -Wall the compiler warns if a later version adds a fourth Error value and this switch forgets it. {4, 200} counts as missing, not invalid, because existence is checked first. The rejected requests left the map untouched: task 7 went from 10 to 15 only through the valid request, and the 0 before it changed nothing. Because apply_all returns counts rather than printing, a test can assert tally.missing == 2 directly, and the application decides the wording. The next lesson returns a value and an error together, for operations like parsing that produce something when they succeed.

Was this article helpful?

Your response is saved on this device.