Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 171 ยท Errors and Debugging

Exception Safety and noexcept

Learn C++ exception safety - the basic, strong and nothrow guarantees, RAII as the foundation, copy-and-swap, noexcept and move_if_noexcept, and why destructors must not throw.

Throwing an exception is easy. The hard part is what happens to everything the exception flies through. Every function between the throw and the catch stops in the middle of its work. Memory it allocated, locks it held and half-updated objects it was modifying are all left as they were at that moment. Exception safety is the discipline of writing code so that this sudden exit never leaks resources or leaves objects in a broken state.

This lesson gives you the vocabulary professionals use (the basic, strong and nothrow guarantees), shows why RAII is the foundation of all of it, and teaches a reliable technique for the strong guarantee. Then it covers noexcept: what it promises, what happens if you break the promise, and why it makes std::vector faster. You'll finish with the rule every C++ programmer must know: destructors don't throw.

What can go wrong

Here's a function written in an old style. It looks fine until you ask "what if something in the middle throws?"

C++
void save_report(Database& db, const Report& r) {
    Buffer* buf = new Buffer(4096);   // 1. acquire memory
    db.lock();                        // 2. acquire a lock
    buf->fill(r);                     // 3. may throw!
    db.write(*buf);                   // 4. may throw!
    db.unlock();
    delete buf;
}

If step 3 throws, unlock() and delete never run. The buffer leaks, and the database stays locked forever, so the next caller hangs. The bug isn't in any single line; it's in the assumption that execution always reaches the end.

You can see the leak happen. Tracer below prints when it's created and destroyed:

C++ A raw pointer leaks, a unique_ptr doesn't

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output shows acquire raw buffer without a matching release: a leak. In the RAII version, release local buffer and release owned buffer both appear before caught. During stack unwinding, C++ destroys every fully constructed local object in reverse order, so anything owned by an object is cleaned up automatically.

The exception safety guarantees

When you document or review a function, you describe what it promises if an exception escapes. There are four levels, from strongest to weakest:

Guarantee Promise if an exception is thrown Typical examples
Nothrow No exception escapes, ever destructors, swap, move operations, std::vector::size()
Strong The operation either succeeds completely or has no effect: state is rolled back std::vector::push_back (with the usual conditions), copy-and-swap assignment
Basic No leaks, all objects still valid and usable, invariants hold; but the state may have changed most operations on most containers
None Anything can happen: leaks, corrupted objects code like save_report above

The basic guarantee is the minimum every function should offer. After a failure, the object might contain different values than before, but you can still use it, assign to it or destroy it safely.

The strong guarantee gives "commit or rollback" semantics, like a database transaction. It's great when callers need it, but it can cost extra copies, so you don't need it everywhere.

The nothrow guarantee is required for a few operations that other guarantees are built on: destructors, deallocation, swap and, ideally, move operations. You can't write a rollback if the rollback itself might fail.

RAII is the foundation

The basic guarantee mostly comes for free when every resource is owned by an object: memory by containers and smart pointers, locks by std::lock_guard, files by std::ofstream. Rewritten in that style, save_report is short and correct:

C++
void save_report(Database& db, const Report& r) {
    auto buf = std::make_unique<Buffer>(4096);
    std::lock_guard lock(db.mutex());   // unlocks in its destructor
    buf->fill(r);
    db.write(*buf);
}                                      // unlock, then delete, on every path

There's no try or catch here at all. That's typical of good C++: you seldom write catch in the middle of a program. Destructors do the cleanup, and only a few places near the top (a request handler, main, a UI event loop) actually catch and report errors.

Achieving the strong guarantee

Leak freedom isn't enough when a half-finished change leaves the object logically wrong. Consider adding several songs to a playlist where one song may be invalid. The basic version leaves a partial update behind:

C++ Basic versus strong guarantee

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

After the failure, playlist a holds ["Intro", "Waves"], a state the caller never asked for. Playlist b still holds ["Intro"], exactly as before the call.

The pattern is always the same:

  1. Do everything that might throw on the side, in a temporary object, without touching the real state.
  2. Commit with operations that cannot throw, such as swap, moving a pointer, or assigning an int.

The best-known form is copy-and-swap assignment, covered in Copy Constructors and Copy Assignment: take the parameter by value (the copy happens there and may throw), then swap it with *this.

The cost is visible too: the strong version copies the whole vector. For a big playlist that may be too expensive, and the basic guarantee plus a clear note in the documentation is a reasonable choice. The standard library makes the same trade-off: std::vector::insert of several elements in the middle gives only the basic guarantee.

noexcept: a promise that nothing escapes

Marking a function noexcept declares that it won't let an exception escape:

C++
int size() const noexcept { return size_; }
void swap(Buffer& other) noexcept;

This is not checked at compile time. If an exception does try to leave a noexcept function, C++ doesn't unwind further: it calls std::terminate, which by default aborts the program. It's a deliberate trade: you give up recovery in exchange for a guarantee that callers and the optimizer can rely on.

C++ Breaking a noexcept promise ends the program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This example fails on purpose. The first call prints first: 7. The second throws inside a noexcept function, so the catch in main never gets a chance. The program stops with terminate called after throwing an instance of 'std::out_of_range' and is killed by SIGABRT. (The std::fflush(stdout) line is there because an aborted program doesn't flush buffered output; without it, even first: 7 would be lost.) Only mark a function noexcept when you're sure that nothing inside it can throw, or that terminating is acceptable if it does.

Conditional noexcept and the noexcept operator

noexcept can take a boolean constant: noexcept(true) is the same as noexcept, and noexcept(false) means "may throw". The noexcept operator asks the compiler whether an expression is declared not to throw, giving a compile-time bool. Templates combine both to say "I'm noexcept if the operations I use are":

C++
template <typename T>
void swap_values(T& a, T& b) noexcept(std::is_nothrow_move_constructible_v<T> &&
                                      std::is_nothrow_move_assignable_v<T>);

Destructors are implicitly noexcept, and so are the special member functions the compiler generates, as long as the members' versions are.

Why noexcept moves make vectors faster

noexcept matters most on move constructors. When a std::vector runs out of capacity, it allocates a bigger block and transfers the elements. Moving is cheap, but if a move threw halfway through, some elements would already be moved out of the old block and the vector couldn't roll back. So to keep push_back's strong guarantee, the vector moves elements only if the move constructor is noexcept (or the type can't be copied). Otherwise it copies them. The helper behind this is std::move_if_noexcept, and you'll see more about this in Move Semantics.

C++ noexcept moves change how a vector grows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Growing to 1,000 elements relocates the contents ten times (capacity 1, 2, 4, โ€ฆ 1,024 in GCC's library) and transfers 1,023 elements in total. The first vector copies all of them; the second moves them. For a type holding strings or buffers, that's the difference between copying megabytes and swapping a few pointers. The practical rule: write noexcept on your move constructor and move assignment whenever they really can't throw, which is almost always. Defaulted ones (= default) get it automatically if every member's move is noexcept.

Destructors must not throw

Destructors run during stack unwinding. If a destructor threw while another exception was already propagating, C++ would have two exceptions at once, and it has no way to handle that, so it calls std::terminate. To avoid that trap altogether, destructors are implicitly noexcept since C++11: a throw that escapes a destructor terminates the program even when no other exception is active.

C++ An exception escaping a destructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This one also fails on purpose: after connection closed cleanly and the flush failed message, the program terminates and the catch block never runs. GCC even warns at compile time, 'throw' will always call 'terminate', with a note that destructors default to noexcept since C++11.

So what should a destructor do when cleanup fails? The established patterns are:

  • Offer an explicit function that can throw, such as close() or commit(), for callers who care about the error. The destructor then only does best-effort cleanup if the caller didn't call it.
  • Swallow and log errors inside the destructor with a try/catch that doesn't rethrow.
  • Keep destructors simple: release memory, close handles, unlock mutexes. Operations that can fail in interesting ways belong in ordinary member functions.

std::ofstream follows the first pattern: its destructor closes the file silently, while close() lets you check whether the final write succeeded, as you'll see in Reading and Writing Text Files.

A checklist for exception-safe code

  • Own every resource with an object: containers, smart pointers, lock guards, streams. Avoid raw new and manual unlock.
  • Aim for the basic guarantee everywhere and the strong guarantee where callers need commit-or-rollback.
  • Do the risky work first on temporaries, then commit with non-throwing operations.
  • Mark swap, move operations and simple getters noexcept, but only when nothing inside can throw.
  • Never let an exception escape a destructor.
  • Catch near the top of the program, where you can actually report or recover, not in every function.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function throws halfway through. Afterward, the object it modified is valid and leak-free, but contains some of the new data. Which guarantee did the function provide?

    The basic guarantee only requires valid objects and no leaks. The strong guarantee would have restored the original state.
  2. 2. What happens when an exception escapes a function declared noexcept?

    noexcept isn't enforced at compile time. A violation at run time calls std::terminate, so no catch block further up can intercept it.
  3. 3. Why does std::vector copy elements instead of moving them during reallocation when the move constructor isn't noexcept?

    Copies leave the originals intact, so a failure can be rolled back. std::move_if_noexcept chooses moving only when it's safe.
  4. 4. In the strong-guarantee pattern, why is the final step a swap?

    All risky work happens on a temporary. The commit must not throw, or the state could end up half-updated again.
  5. 5. A class's destructor contains throw std::runtime_error("x"); that runs. No other exception is active. What happens?

    Since C++11 destructors are noexcept by default, so any exception leaving one calls std::terminate.

Summary

  • An exception can stop any function midway; exception-safe code never leaks and never leaves broken objects.
  • The guarantees are nothrow (never throws), strong (commit or rollback), basic (valid and leak-free) and none. Aim for basic everywhere.
  • RAII gives you the basic guarantee almost for free: destructors run during stack unwinding.
  • For the strong guarantee, work on a copy and commit with a non-throwing swap.
  • noexcept is a promise; breaking it calls std::terminate. Mark moves and swaps noexcept so containers can move instead of copy.
  • Destructors are implicitly noexcept and must never throw; provide an explicit close() for errors callers need to see.

Next: Error Handling Without Exceptions, where you'll compare error codes, std::optional and std::expected.