Interview Q&A · C++ · 12 questions in this topic
Exception Handling & RAII Safety — C++ Interview Q&A
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
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
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
- 1Nothrow — never emits; cleanup operations.
- 2Strong — commit-or-rollback; copy-and-swap idiom.
- 3Basic — valid state, no leaks; the minimum everywhere.
Example
// copy-and-swap: strong guarantee Widget& Widget::operator=(Widget other) noexcept { swap(*this, other); // commit cannot fail after the copy return *this; }
What does `noexcept` mean and when should you use it?
Answer
noexcept declares a function will not emit exceptions — violations call std::terminate. Use it for destructors, moves, swaps and deallocation paths. It also unlocks optimizations: containers move (rather than copy) elements during growth only when moves are noexcept.
Do not mark functions noexcept unless the promise holds on every path, including called code.
Example
struct Buffer { Buffer(Buffer&& other) noexcept; // enables vector growth via moves }; static_assert(std::is_nothrow_move_constructible_v<Buffer>);
💡 Moves and swaps want noexcept — that is the highest-value place to write it.
Throw by value, catch by reference — why?
Answer
Throwing by value preserves the dynamic type in the exception object (throwing a pointer risks lifetime and ownership bugs). Catching by const reference avoids slicing and extra copies while letting one handler serve a whole hierarchy (catch Base& catches Derived too).
Order handlers derived-first: a base handler placed first swallows derived exceptions before their specific handler runs.
Example
try { throw DerivedError(); } catch (const DerivedError& e) { /* specific first */ } catch (const BaseError& e) { /* general after */ }
What is the difference between `throw;` and `throw e;` inside a catch block?
Answer
Bare throw; rethrows the current exception object preserving its dynamic type. throw e; throws a copy of the static-typed variable e — slicing a derived exception down to the base. Always prefer bare throw; when propagating.
The same slicing rule applies to return-by-value of caught exceptions.
Example
catch (const Base& e) { // throw e; // slices to Base! throw; // rethrows original dynamic type }
💡 Bare throw preserves type, named throw slices — that contrast is the whole answer.
What should you derive custom exceptions from?
Answer
Derive from std::exception (or its children runtime_error/logic_error) so generic catch (const std::exception&) handlers work. Override what() with a noexcept message, keep exceptions copyable, and put them in a project namespace.
Value semantics matter: exceptions are copied during propagation, so throwing non-copyable or resource-owning types without care breaks.
Example
#include <stdexcept> class ConfigError : public std::runtime_error { public: using std::runtime_error::runtime_error; };
Exceptions vs error codes — when is each appropriate?
Answer
Exceptions suit rare, non-local failures where the call stack cannot proceed (I/O failure, bad config, invariant violation) — they cannot be ignored and they separate happy paths from error paths. Error codes/expected suit hot paths, recoverable/local failures, and no-exception environments (games, kernels, -fno-exceptions codebases).
C++23 std::expected gives a middle path: explicit error values without exception overhead.
Key points
- 1Exceptions — rare, exceptional, cannot-continue-here failures.
- 2Codes/expected — hot, local, recoverable, or noexcept-required code.
Example
// C++23: explicit error without exceptions // std::expected<int, std::string> parse(std::string_view s);
💡 Rare-and-nonlocal vs hot-and-local is the decision rule interviewers want.
What happens if an exception escapes a destructor or a noexcept function?
Answer
A destructor throwing during stack unwinding triggers std::terminate (two live exceptions cannot coexist). A noexcept function that emits calls std::terminate immediately. Both end the program — no handler runs.
Hence: destructors are implicitly noexcept, swallow or log internal failures, and cleanup code never calls throwing operations unguarded.
Example
struct Guard { ~Guard() noexcept { // must not throw try { flush(); } catch (...) { /* log, swallow */ } } };
What is `std::terminate`, `std::unexpected` and `std::uncaught_exceptions`?
Answer
std::terminate ends the program (default: abort) when exception handling fails — uncaught exception, noexcept violation, double-throw during unwinding. std::unexpected is the legacy dynamic-specification handler (removed in C++17). std::uncaught_exceptions() counts live propagating exceptions, letting scope guards distinguish normal exit from unwinding.
Custom terminate handlers log diagnostics before aborting in production services.
Example
#include <exception> std::set_terminate([]{ // log last-chance diagnostics, then abort std::abort(); });
How do you write exception-safe code with raw resources (the hard way)?
Answer
Scope every acquisition in a guard so every path releases: lock_guard for mutexes, unique_ptr with custom deleters for handles, and copy-and-swap for assignment. Order operations so throwing steps precede commits (allocate before mutating), and never let owning raw pointers cross function boundaries.
The real answer: wrap once in an RAII type, then never repeat the manual pattern — the manual version exists only to justify the wrapper.
Example
void update(Widget& w) { auto next = std::make_unique<Buffer>(w.size()); // may throw: w untouched fill(*next); // may throw: w untouched w.commit(std::move(next)); // commit: nothrow swap }
💡 Throwing work before nothrow commit is the exception-safe ordering pattern.
Should constructors throw? What are the alternatives?
Answer
Yes — throwing is the cleanest way to signal construction failure, since constructors have no return value. The half-built object unwinds automatically (fully-constructed members destroy themselves). Alternatives are two-phase init (weakened invariants), factory functions returning expected/optional, or tagged invalid states — all weaker than an exception for genuine failures.
Never leave a zombie object: either the constructor establishes the invariant or it throws.
Example
class Port { public: explicit Port(int n) { if (!open(n)) throw std::runtime_error("no port"); } };
Recommended resourcesAffiliate links · may earn us a commission