Error handling: exceptions, optional and expected
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Things go wrong
Files are missing. Users type letters where numbers were expected. Networks drop. A program that ignores this works in the demo and fails in production. C++ gives you several ways to report and handle errors, and the skill is picking the right one for each situation.
Exceptions
An exception is an object that you throw when a function cannot do what it promised. The stack unwinds, destroying local objects (this is where RAII earns its keep), until a matching catch block is found.
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
std::vector<std::string> readLines(const std::string& path) {
std::ifstream in{path};
if (!in) {
throw std::runtime_error("cannot open file: " + path);
}
std::vector<std::string> lines;
std::string line;
while (std::getline(in, line)) lines.push_back(line);
return lines;
}
int main() {
try {
auto lines = readLines("data.txt");
std::cout << lines.size() << " lines\n";
} catch (const std::runtime_error& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}
Catch by const reference. Catching by value copies the exception and can slice a derived exception down to its base class. The standard exceptions all derive from std::exception, which provides what(). The useful ones: std::invalid_argument for bad inputs, std::out_of_range for bad indexes, std::runtime_error for failures that could not be foreseen from the arguments, and std::logic_error for bugs in the calling code.
Your own exception types
class ParseError : public std::runtime_error {
public:
ParseError(const std::string& msg, int line)
: std::runtime_error{msg + " (line " + std::to_string(line) + ")"}, line_{line} {}
int line() const { return line_; }
private:
int line_;
};
// throw ParseError{"missing comma", 12};
Order catch blocks from the most specific to the most general. A catch (...) block catches anything, which is useful at the top of a program or a thread, to log and exit cleanly, but not as a habit in the middle of the code.
When exceptions are the right tool
Use exceptions for errors that are unexpected at the call site and that the immediate caller cannot sensibly handle: the file that should exist does not, memory ran out, a constructor cannot build a valid object. Constructors have no return value, so exceptions are the only clean way to report a failure there.
Do not use exceptions for ordinary control flow. "The user typed a name that is not in the list" is not exceptional. It is a normal outcome, and you want a normal return value.
std::optional: a value that may be missing
When "no result" is a normal answer, return std::optional<T>. It holds either a T or nothing.
#include <optional>
#include <string>
#include <vector>
struct User { int id; std::string name; };
std::optional<User> findUser(const std::vector<User>& users, int id) {
for (const auto& u : users) {
if (u.id == id) return u;
}
return std::nullopt;
}
int main() {
std::vector<User> users{{1, "Asha"}, {2, "Bilal"}};
if (auto u = findUser(users, 2)) {
std::cout << u->name << "\n";
} else {
std::cout << "no such user\n";
}
std::cout << findUser(users, 9).value_or(User{0, "guest"}).name << "\n";
}
The type documents the possibility of absence, and callers cannot forget to check as easily as they can with a null pointer. value_or supplies a default. Calling value() on an empty optional throws std::bad_optional_access, while dereferencing an empty optional with * is undefined behaviour, so check first.
std::expected: a value or an error
C++23 adds std::expected<T, E>. It holds either the successful value or an error value that says what went wrong. It suits operations like parsing, where failure is common and you want a reason, not just "nothing".
#include <charconv>
#include <expected>
#include <string>
#include <string_view>
enum class ParseFail { Empty, NotANumber };
std::expected<int, ParseFail> parseInt(std::string_view text) {
if (text.empty()) return std::unexpected{ParseFail::Empty};
int value{};
auto [end, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
if (ec != std::errc{} || end != text.data() + text.size())
return std::unexpected{ParseFail::NotANumber};
return value;
}
int main() {
auto r = parseInt("123");
if (r) std::cout << *r << "\n";
else std::cout << "parse failed\n";
}
This needs a compiler and standard library that supports C++23 <expected>. Recent GCC, Clang and MSVC releases do, but check yours, since support depends on the version. If you do not have it, std::optional or a small struct holding a value and an error code does the same job.
Exception safety
When a function throws, what state is your data left in? There are three levels worth knowing.
- Basic guarantee: nothing leaks and the object is still valid, though its value may have changed.
- Strong guarantee: the operation either completes or has no effect, as if it never ran.
- No-throw guarantee: it never throws. Mark such functions
noexcept.
RAII gives you the basic guarantee almost for free. For the strong guarantee, a common technique is to do the risky work on a copy and then swap it in with a no-throw operation. Move operations and destructors should be noexcept. If an exception escapes from a noexcept function, the program calls std::terminate.
Choosing
| Situation | Tool |
|---|---|
| Constructor cannot build a valid object | Exception |
| Lookup may legitimately find nothing | std::optional |
| Operation fails often and you need the reason | std::expected or an error code |
| Cannot recover at all | Log and exit |
The common mistake
Swallowing errors with an empty catch (...) {}. The program carries on in an unknown state and fails later in a place nobody can trace. The second mistake is manual cleanup next to a throw, such as new followed by delete with a throwing call between them. The third is throwing from a destructor.
Try it yourself
- Write
double safeDivide(double a, double b)that throwsstd::invalid_argumentwhenbis zero, and amainthat handles it. - Write
std::optional<double> parseDouble(const std::string&)usingstd::stodinside a try block, returningnullopton failure. - Make a custom exception
InsufficientFundsthat carries the shortfall amount, and use it in theBankAccountclass from an earlier lesson.
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
std::vector<std::string> readLines(const std::string& path) {
std::ifstream in{path};
if (!in) {
throw std::runtime_error("cannot open file: " + path);
}
std::vector<std::string> lines;
std::string line;
while (std::getline(in, line)) lines.push_back(line);
return lines;
}
int main() {
try {
auto lines = readLines("data.txt");
std::cout << lines.size() << " lines\n";
} catch (const std::runtime_error& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account