C++ Beginner · Lesson 22 of 22
Error handling patterns
Return codes, exceptions, std::optional results, and choosing between them.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain error handling patterns in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
There are three common patterns. Exceptions suit rare, serious failures. Return codes or bool suit hot paths and C-style APIs. std::optional<T> (C++17) or a small result struct suits 'the value might not exist' without any exception cost. Pick one pattern per layer and document it.
Distinguish expected failures (a sensor read timed out) from programming errors (an index out of range). Handle the first, assert on the second. Never ignore an error result; the compiler can help with [[nodiscard]].
Guided lesson
Work through these steps
- 1.
Read the error handling patterns example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <optional>
// Header for std::optional (C++17).
#include <string>
// Header for the error message type.
[[nodiscard]] std::optional<double> read_sensor(bool connected) {
// [[nodiscard]] warns if a caller ignores the result.
if (!connected) return std::nullopt;
// No value: report 'nothing' instead of a fake number.
return 21.5;
// A valid reading.
}
// End of read_sensor.
struct Result { bool ok; std::string message; };
// A tiny result type when you need a reason for failure.
Result start(bool port_free) {
// A function that reports why it failed.
if (!port_free) return {false, "port busy"};
// Failure with an explanation.
return {true, ""};
// Success, no message.
}
// End of start.
if (auto v = read_sensor(true)) std::cout << *v << '\n';
// Test the optional, then use * to read the value inside.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Error handling patterns. Expected result: 21.5 no reading
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
#include <optional>
// TODO: return std::nullopt when not connected, otherwise 21.5
int main() {
if (auto v = read_sensor(true)) std::cout << *v << '\n';
if (auto v = read_sensor(false)) std::cout << *v << '\n';
else std::cout << "no reading\n";
return 0;
}Expected output
21.5
no readingStuck? Show the full solution (try it yourself first)
#include <iostream>
#include <optional>
std::optional<double> read_sensor(bool connected) {
if (!connected) return std::nullopt;
return 21.5;
}
int main() {
if (auto v = read_sensor(true)) std::cout << *v << '\n';
if (auto v = read_sensor(false)) std::cout << *v << '\n';
else std::cout << "no reading\n";
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Implement one function three ways: throwing an exception, returning bool plus an out-parameter, and returning std::optional. Write a short note on which one you would use in a 1 kHz loop and which at start-up.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.