C++ Beginner · Lesson 21 of 22
Exceptions
try, catch, throw, exception types, and safe cleanup during unwinding.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain exceptions 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
An exception reports an error that the current function cannot handle. throw leaves the function immediately, destroys local objects (which is why RAII is important) and continues in the nearest matching catch. Throw objects derived from std::exception, such as std::runtime_error, and catch by const reference.
Use exceptions for exceptional failures, such as a device missing at start-up, not for ordinary control flow. Mark functions that cannot fail noexcept; destructors are noexcept by default. ROS 2 code commonly catches exceptions at the node boundary.
Guided lesson
Work through these steps
- 1.
Read the exceptions 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 <stdexcept>
// Header for std::runtime_error and friends.
double parse_speed(double raw) {
// A function that validates its input.
if (raw < 0.0) throw std::invalid_argument("speed must be >= 0");
// Report a programming/input error by throwing.
return raw;
// Valid input passes through.
}
// End of parse_speed.
try {
// Code that may throw goes inside try.
double s = parse_speed(-3.0);
// This throws, so the next lines are skipped.
std::cout << s << '\n';
// Not reached.
} catch (const std::invalid_argument& e) {
// Catch this specific error by const reference.
std::cerr << "error: " << e.what() << '\n';
// what() returns the message given to the exception.
}
// Execution continues here; local objects were cleaned up automatically.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 Exceptions. Expected result: error: speed must be >= 0 speed 2.5
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 <stdexcept>
double parse_speed(double raw) {
// TODO: throw std::invalid_argument("speed must be >= 0") when raw is negative
return raw;
}
int main() {
// TODO: call parse_speed(-3.0) inside try and print "error: " + e.what() in a catch block
std::cout << "speed " << parse_speed(2.5) << '\n';
return 0;
}Expected output
error: speed must be >= 0
speed 2.5Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <stdexcept>
double parse_speed(double raw) {
if (raw < 0.0) throw std::invalid_argument("speed must be >= 0");
return raw;
}
int main() {
try {
parse_speed(-3.0);
} catch (const std::invalid_argument& e) {
std::cout << "error: " << e.what() << '\n';
}
std::cout << "speed " << parse_speed(2.5) << '\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
Write open_device(name) that throws std::runtime_error when name is empty. Call it inside try/catch, print e.what(), and show that a RAII object in the try block is destroyed during unwinding.
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.