Lesson 29 of 45 · C++
Lesson 35: Exception Handling
Duration: 11 min
Lesson 29 of 45 · C++
Duration: 11 min
try, catch, and throw. Exceptions unwind the stack, invoking destructors of all objects with automatic storage, which enables RAII‑based cleanup.\n\n---\n\n## Basic pattern\ncpp\ntry {\n // Code that may throw\n if (somethingBad()) throw std::runtime_error(\"something went wrong\");\n std::cout << \"All good\\n\";\n} catch (const std::exception& e) {\n std::cerr << \"Error: \" << e.what() << '\\n';\n}\n\n\n## Custom exception type\ncpp\nclass MyError : public std::exception {\n std::string msg;\npublic:\n explicit MyError(std::string m) : msg(std::move(m)) {}\n const char* what() const noexcept override { return msg.c_str(); }\n};\n\nvoid mayFail(bool flag) {\n if (flag) throw MyError(\"Flag was true\");\n}\n\n\n## Exception safety guarantees\n- no‑throw – functions guarantee they never throw (noexcept).\n- strong – if an exception occurs, the program state remains unchanged.\n- basic – resources are not leaked, but state may be partially modified.\n\n> Tip: Prefer RAII wrappers (e.g., std::lock_guard) to ensure resources are released even when an exception occurs.\n\n---\n\n<Alert type="info">Mark move constructors/assignment operators as noexcept to enable containers (like vector) to use them during reallocation.