Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 29 of 45 · C++

Lesson 35: Exception Handling

Duration: 11 min

Exception Handling\n\nC++ 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.\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.

Previous: Lesson 34: Lambda ExpressionsNext: Lesson 36: File I/O Streams