Skip to content

C++ Flashcards: Error Handling

C++ — Error Handling Flashcards

20 interactive flashcards. Press Space to flip, rate 1-4 to schedule next review.


Intuition

Error handling is about graceful recovery when things go wrong. Exceptions let you separate the “happy path” from error recovery, throw when something fails, catch where you can recover. Think of stack unwinding as a domino effect: when an exception is thrown, each local object’s destructor runs as the call stack collapses, cleaning up resources automatically. Modern C++ also offers std::optional for “may not have a value” and std::expected (C++23) for “may have an error.”

Common Pitfalls

  • Throwing in destructors: If a destructor throws during stack unwinding from another exception, std::terminate is called immediately, always mark destructors noexcept or catch internally.
  • Exception specifications: The old throw() syntax is deprecated, use noexcept instead, and understand that noexcept functions that do throw will call std::terminate.
  • Catching by value: Catching exceptions by value causes slicing, always catch by reference (catch (const std::exception& e)).

Cross-References

  • Lambdas: Lambda expressions that can be used in error handling patterns.
  • Memory Management: RAII and smart pointers that provide exception-safe resource management.
  • Object-Oriented Programming: OOP patterns for error handling hierarchies.