Exceptions and Resource Management (C++ Core #9)
Exceptions move control from the point of failure to the nearest handler, and on the way out they destroy every automatic object in between. That unwinding is the mechanism, and RAII is the practice built on it: put the cleanup in a destructor and it runs whether the function returns or throws.
try, catch, and throw
try {
throw std::runtime_error("disk full");
} catch (const std::runtime_error& e) {
std::cout << e.what() << '\n'; // disk full
} catch (const std::exception& e) {
// base-class handler, catches other standard exceptions
} catch (...) {
// catches everything, including non-std types
}
Handlers are checked top to bottom, and the first match wins. A handler for a base class catches derived exceptions, so order matters: specific before general.
Catch by reference, not by value. By value slices the exception object (Ch. 4) and copies it; by pointer is worse, because the pointer may refer to a destroyed temporary.
catch (const MyError& e) { } // correct
catch (MyError e) { } // slices, copies
catch (MyError* e) { } // almost always a bug
throw; inside a handler rethrows the current exception without copying it. Use it
when you want to log and let the caller handle the error.
catch (std::exception e) lose information?ASolution
It constructs a new std::exception by slicing the thrown object, so the
derived part and its overridden what() are gone. Catch by const&.
Stack unwinding
When an exception is thrown, the runtime destroys every automatic object between the throw and the matching handler, innermost first. Then control jumps to the handler.
struct A { ~A() { std::cout << "~A\n"; } };
struct B { ~B() { std::cout << "~B\n"; } };
void f() { A a; throw std::runtime_error("x"); }
void g() { B b; f(); }
int main() {
try { g(); }
catch (const std::exception& e) { std::cout << e.what() << '\n'; }
}
// ~A
// ~B
// x
a is destroyed as f unwinds, then b as g unwinds. The handler runs after
both destructors.
If a destructor throws during unwinding, the runtime has two live exceptions and
calls std::terminate. That is why destructors are implicitly noexcept since
C++11.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.2cm, minimum height=0.55cm, font=\scriptsize, align=center},
a/.style={->, thick}]
\node[b, fill=green!18] (m) at (0,0) {main\\try};
\node[b, fill=blue!12] (g) at (0,-1.0) {g\\B b};
\node[b, fill=blue!12] (f) at (0,-2.0) {f\\A a};
\node[b, fill=red!15] (t) at (0,-3.0) {throw};
\draw[a] (m) -- (g); \draw[a] (g) -- (f); \draw[a] (f) -- (t);
\draw[->, very thick, orange] (1.6,-3.0) .. controls (3.2,-2.0) .. (1.6,0);
\node[font=\scriptsize, anchor=west, text=orange!80!black] at (2.0,-1.6) {unwind: ~A, then ~B};
\end{tikzpicture}
Objects on the heap are not destroyed. A new-allocated object only dies if
something deletes it; if the pointer was a local raw pointer, the unwinding only
destroys the pointer, and the object leaks. That is the entire argument for RAII.
new, then throws before deleting. Whathappens to the allocation?
ASolution
It leaks. Unwinding destroys automatic objects, not heap objects. Wrapping the
pointer in std::unique_ptr fixes it, because the smart pointer’s destructor
runs.
Exception safety guarantees
Three levels, from weakest to strongest:
| Guarantee | Promise |
|---|---|
| no-throw | the operation never throws |
| strong | if it throws, the object is unchanged (commit or rollback) |
| basic | if it throws, the object is valid but maybe changed; no leaks |
std::vector::push_back gives the strong guarantee when the element’s copy or move
constructor does not throw. It allocates a new buffer, copies or moves, and only
then swaps — if the copy throws, the old buffer is untouched. That copy-and-swap
pattern is the standard way to get the strong guarantee.
Buffer& operator=(const Buffer& o) {
Buffer tmp(o); // may throw; *this untouched
swap(*this, tmp); // noexcept
return *this; // tmp's destructor releases the old buffer
}
swap should be noexcept, because it is the commit step. If the commit can
throw, the strong guarantee is not possible.
std::vector::insert in the middle is weaker than push_back: moving later
elements can throw, so the standard only promises basic safety in that case.
ASolution
Strong means “all or nothing”: on failure the object looks exactly as it did before. Basic means “no leak, still valid”, but the contents may have changed.
RAII and exception safety
RAII (Resource Acquisition Is Initialization) makes resource acquisition and release automatic: acquire in the constructor, release in the destructor. The destructor is the only code guaranteed to run on every exit path.
class File {
std::FILE* f;
public:
explicit File(const char* path) : f(std::fopen(path, "r")) {
if (!f) throw std::runtime_error("open failed");
}
~File() { if (f) std::fclose(f); }
File(const File&) = delete;
File& operator=(const File&) = delete;
std::FILE* get() const { return f; }
};
void read() {
File f("data.txt"); // may throw, nothing to clean up if it does
parse(f.get()); // may throw, f closes on unwind
}
The standard library is built this way: std::vector, std::string,
std::unique_ptr, std::lock_guard, std::fstream. lock_guard is the smallest
example:
std::mutex m;
void f() {
std::lock_guard<std::mutex> lock(m); // locks
doWork(); // may throw
} // unlocks, always
Without the guard, every return and every exception path needs an explicit
unlock(), and one missed path deadlocks the program.
C++ has no finally. The replacements are RAII and a scope guard:
template <class F>
struct ScopeGuard {
F f;
~ScopeGuard() noexcept { f(); }
};
finally?ASolution
A destructor runs on normal return, early return, and exception unwinding, so the cleanup is written once and cannot be skipped.
Constructor failure
If a constructor throws, the object is never created. Its destructor does not run. But base classes and members that were already constructed are destroyed.
struct M {
M() { std::cout << "M ctor\n"; }
~M() { std::cout << "M dtor\n"; }
};
struct S {
M m;
S() { throw std::runtime_error("fail"); }
~S() { std::cout << "S dtor\n"; }
};
try { S s; } catch (...) { }
// M ctor
// M dtor
// no "S dtor"
That asymmetry is the reason a constructor that allocates two resources must clean up the first if the second fails. RAII members solve it: the first member’s destructor runs during unwinding.
class Two {
std::unique_ptr<int[]> a;
std::unique_ptr<int[]> b;
public:
Two() : a(new int[10]), b(new int[10]) {} // if b throws, a is freed
};
~S() run when S’s constructor throws?ASolution
No. The object was never fully constructed. Members and bases that finished construction are destroyed, and the memory is released.
Destructor behaviour
Destructors are implicitly noexcept since C++11. Throwing from one is a
terminate call, not an exception the caller can catch.
struct Bad {
~Bad() { throw std::runtime_error("boom"); } // std::terminate
};
If a destructor throws while another exception is already propagating, the program
terminates immediately. If it throws with no exception in flight, it still
terminates (because the destructor is noexcept).
A destructor that must do fallible work should catch its own exceptions and log or ignore them:
~Connection() {
try { flush(); }
catch (const std::exception& e) { log(e.what()); }
}
noexcept(false) is possible but should be reserved for types where destruction
cannot fail, or where the caller explicitly knows the risk.
std::terminate?
ASolution
The runtime already has an exception in flight. A second one cannot propagate
from a destructor, so the standard calls terminate rather than losing one of
them.
noexcept
noexcept is a promise that a function does not throw. If it does, std::terminate
is called.
void f() noexcept; // must not throw
void g() noexcept(false); // may throw
void h() noexcept(noexcept(g())); // conditional
Since C++17, noexcept is part of the function type, so void(*)() and
void(*)() noexcept are different types.
Why it matters:
- Move semantics.
std::vectormoves elements during reallocation only if the move constructor isnoexcept; otherwise it copies to preserve the strong guarantee. Mark move operationsnoexcept. - Performance. The compiler can skip landing pads and unwinding tables for calls it knows cannot throw.
- Correctness.
std::terminateis a harsh failure mode; do not mark functionsnoexceptunless they really cannot throw.
Buffer(Buffer&& o) noexcept; // correct
Buffer& operator=(Buffer&& o) noexcept; // correct
void parse() noexcept; // wrong if parse can throw
noexcept?ASolution
Containers use moves only when they are noexcept, because a throwing move
cannot provide the strong guarantee. Without it, vector copies instead, which
is slower.
Exceptions versus error codes
| Exceptions | Error codes | |
|---|---|---|
| Propagation | automatic, any depth | manual, every level |
| Ignoring | cannot be silently ignored | easy to ignore |
| Cost | zero when not thrown; expensive when thrown | one branch per call |
| Use for | exceptional conditions, constructors | expected failures, hot paths |
Exceptions are the only way for a constructor to signal failure, since it cannot
return a value. Error codes are better for expected, frequent failures and for
code compiled without exceptions (-fno-exceptions, common in embedded and some
game engines).
Standard exception types to know:
| Type | Meaning |
|---|---|
std::exception |
base, what() |
std::runtime_error |
general runtime failure |
std::logic_error |
programmer error |
std::out_of_range |
index or range |
std::invalid_argument |
bad parameter |
std::bad_alloc |
allocation failed |
std::bad_cast |
failed dynamic_cast reference |
ASolution
A constructor has no return value. It either completes or throws. Static factory
functions and std::optional are the alternatives when exceptions are disabled.
Bugs and edge cases
- Catching by value. Slices the exception and loses the derived
what(). - Catching by pointer. The exception object is destroyed when the handler exits; a stored pointer dangles.
- Throw in a destructor.
std::terminate, especially during unwinding. - Leaking on early return. Every
newbefore athrowmust be owned by RAII. - Exception in a
noexceptfunction. Immediate terminate, no diagnostic. - Assuming unwinding destroys heap objects. It does not.
- Losing the original exception. Catching and throwing a new type without
throw;hides the cause. - Exceptions across C boundaries. C code has no unwinding; throwing through a C callback is UB unless the interface is designed for it.
std::bad_allocassumptions.newcan throw;nothrowreturns null;vectormay throwlength_errorbefore allocating.
catch (...) block swallows an exception and the program continuesin a broken state. What is the better pattern?
ASolution
Catch only what you can handle, clean up with RAII, and rethrow with throw;
what you cannot. A blanket catch should be the last line of defence that logs
and terminates, not a way to ignore errors.
Next: The C++ Standard Library (C++ Core #10) — containers, iterators, algorithms, and the vocabulary types.