Module 20: Exception HandlingIntermediate45 min read
Exception Handling: try/catch/throw, Stack Unwinding & Custom Exceptions
Handle runtime errors cleanly with try/catch/throw, std::exception subclasses, stack unwinding with RAII, and noexcept guarantees.
Key Takeaways & Core Concepts
- Basic: No leaks, invariants preserved.
- Strong: Commit-or-rollback semantics.
- Nothrow (`noexcept`): Guaranteed never to throw (critical for destructors and move constructors!).
1. `try` / `catch` / `throw` & Stack Unwinding
When throw executes, normal flow aborts and the runtime unwinds the call stack, calling destructors of every stack-allocated (RAII) object until a matching catch handler is reached.
1. Custom Exception Class & Catch-All Handler
1#include <iostream>
2#include <stdexcept>
3#include <string>
4
5class BalanceError : public std::runtime_error {
6public:
7 explicit BalanceError(const std::string& msg) : std::runtime_error(msg) {}
8};
9
10void withdraw(double bal, double amt) {
11 if (amt > bal) throw BalanceError("Insufficient funds!");
12}
13
14int main() {
15 try {
16 withdraw(100.0, 250.0);
17 } catch (const BalanceError& e) {
18 std::cout << "Caught: " << e.what() << "\n";
19 }
20 return 0;
21}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
21 lines
Note: Custom exception inheriting from `std::runtime_error` caught by `const` reference.
2. Standard Exception Hierarchy & Custom Exceptions
Derive custom exceptions from std::runtime_error or std::exception. Always throw by value and catch by `const` reference (catch (const std::exception& e)) to prevent object slicing.
3. Exception Safety Guarantees & `noexcept`
- Basic: No leaks, invariants preserved.
- Strong: Commit-or-rollback semantics.
- Nothrow (`noexcept`): Guaranteed never to throw (critical for destructors and move constructors!).
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)