Lesson 35 of 45
C++Lesson 35: Exception Handling
11 min
Course progress78%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 35 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
C++ provides a robust mechanism for error propagation using try, catch, and throw. Exceptions unwind the stack, invoking destructors of all objects with automatic storage, which enables RAII‑based cleanup.
try {
// Code that may throw
if (somethingBad()) throw std::runtime_error(\"something went wrong\");
std::cout << \"All good\
\";
} catch (const std::exception& e) {
std::cerr << \"Error: \" << e.what() << '\
';
}
class MyError : public std::exception {
std::string msg;
public:
explicit MyError(std::string m) : msg(std::move(m)) {}
const char* what() const noexcept override { return msg.c_str(); }
};
void mayFail(bool flag) {
if (flag) throw MyError(\"Flag was true\");
}
noexcept).Tip: Prefer RAII wrappers (e.g.,
std::lock_guard) to ensure resources are released even when an exception occurs.
<Alert type="info">Mark move constructors/assignment operators as noexcept to enable containers (like vector) to use them during reallocation.