Interview Q&A · C++ · 12 questions in this topic

Exception Handling & RAII Safety — C++ Interview Q&A

All C++ topics

Throwing, catching and surviving exceptions — guarantees, noexcept, and why RAII beats manual cleanup. Part of Exception Handling · 213 questions in the C++ bank.

How do try, catch and throw work in C++?

Answer

Code that may fail runs in try; throw transfers control to the matching catch by walking the stack outward, running destructors along the way (stack unwinding). Handlers match by type (derived-to-base order matters), catch(...) catches everything, and an uncaught exception calls std::terminate.

Throw by value, catch by (const) reference — catching by value slices derived exceptions.

Example

Example.cppcpp
try {
    throw std::runtime_error("disk full");
} catch (const std::runtime_error& e) { // by const ref: no slicing
    // handle
} catch (...) { /* everything else */ }

What is stack unwinding?

Answer

When an exception propagates, the runtime destroys automatic objects in each exited scope (in reverse construction order) as it searches for a handler. That is why RAII cleanup is exception-safe: every owned resource releases exactly once on every path, taken or exceptional.

If a destructor throws during unwinding, terminate follows — hence the never-throw destructor rule.

Example

Example.cppcpp
void f() {
    std::lock_guard<std::mutex> g(m); // destroyed during unwinding
    throw std::runtime_error("x");  // g unlocks on the way out
}

💡 Unwinding runs destructors — that single fact is the bridge between exceptions and RAII.

What are the exception safety guarantees (basic, strong, nothrow)?

Answer

Nothrow guarantees no exception escapes (swap, moves, destructors should aim here). Strong guarantees all-or-nothing — full commit or full rollback (copy-and-swap gives this). Basic guarantees no leaks and valid (possibly changed) state. No guarantee means anything may be broken.

Design guideline: provide strong where rollback is cheap, basic everywhere, nothrow for cleanup paths.

Key points

  1. 1Nothrow — never emits; cleanup operations.
  2. 2Strong — commit-or-rollback; copy-and-swap idiom.
  3. 3Basic — valid state, no leaks; the minimum everywhere.

Example

Example.cppcpp
// copy-and-swap: strong guarantee
Widget& Widget::operator=(Widget other) noexcept {
    swap(*this, other); // commit cannot fail after the copy
    return *this;
}

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits