C++ Exception Handling | try, catch, throw, and RAII

C++ Exception Handling | try, catch, throw, and RAII

이 글의 핵심

From basic try/catch to RAII, slicing avoidance, and choosing between exceptions and error codes.

Basics

try {
    throw std::runtime_error("failure");
} catch (const std::runtime_error& e) {
    std::cerr << e.what() << '\n';
}

Catch by reference

Prefer const std::exception& (or specific types) to avoid object slicing when catching polymorphic exceptions.

Standard hierarchy

std::exceptionstd::logic_error, std::runtime_error, and more specific types (invalid_argument, out_of_range, …).

Exception safety

  • Basic: no leaks; invariants may be broken mid-operation.
  • Strong: commit-or-rollback (e.g. copy-and-swap).
  • Nothrow: operation does not throw (noexcept).

RAII

Acquire resources in constructors; release in destructors so stack unwinding cleans up automatically.

Exceptions vs error codes

ExceptionsOutcome types / codes
FlowFor exceptional failureFor frequent, expected failure
API visibilityNot always obvious from signature (pre-contracts)Often explicit in return type

std::expected (C++23) models value-or-error explicitly.


  • Exception specifications
  • noexcept

Keywords

C++, exceptions, try, catch, throw, RAII