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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 35: Exception Handling | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Try‑catch‑throw mechanics
  • Custom exception classes
  • Exception safety levels
  • Standard exception hierarchy

Exception Handling

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.


Basic pattern

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() << '\
';
}

Custom exception type

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\");
}

Exception safety guarantees

  • no‑throw – functions guarantee they never throw (noexcept).
  • strong – if an exception occurs, the program state remains unchanged.
  • basic – resources are not leaked, but state may be partially modified.

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.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 34: Lambda ExpressionsContinue to lesson 36Lesson 36: File I/O StreamsBack to C++ Course curriculum