Exceptions

Exceptions in C++: A recipe does not tell you what to do if the kitchen catches fire. It carries on describing how to fold the eggs, because handling a fire is…

The Analogy: The Fire Alarm

A recipe does not tell you what to do if the kitchen catches fire. It carries on describing how to fold the eggs, because handling a fire is not the recipe's job — you leave the room, and someone trained deals with it.

An exception is that alarm. When a function discovers it cannot do what it was asked, it throws, and control leaves immediately — out of the loop, out of the function, out of its caller — until it reaches something equipped to handle the situation. Everything in between is skipped, but critically, everything in between is still cleaned up: as the stack unwinds, every local object's destructor runs. That is why exceptions and RAII are two halves of one design.

The trade-off is that exceptions are for the exceptional. A missing file the user typed wrongly is an expected outcome and deserves a return value; a configuration file that must exist for the program to run at all is a genuine emergency.


Syntax or Core Structure

#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>

double divide(double a, double b) {
    if (b == 0.0) {
        throw std::invalid_argument("division by zero");
    }
    return a / b;
}

int main() {
    try {
        std::cout << divide(10.0, 2.0) << "\n";     // 5
        std::cout << divide(1.0, 0.0) << "\n";      // throws -- never prints
        std::cout << "unreachable\n";
    }
    catch (const std::invalid_argument& e) {         // most specific first
        std::cout << "bad argument: " << e.what() << "\n";
    }
    catch (const std::exception& e) {                // then the general case
        std::cout << "error: " << e.what() << "\n";
    }

    // Standard library functions throw too.
    std::vector<int> v{1, 2, 3};
    try {
        std::cout << v.at(10) << "\n";              // throws std::out_of_range
    }
    catch (const std::out_of_range& e) {
        std::cout << "out of range: " << e.what() << "\n";
    }

    std::cout << "still running\n";
    return 0;
}

Three habits visible there: catch by const reference, list handlers most specific first, and let what() carry the detail.


Technical Depth: Unwinding, Safety and Cost

The standard hierarchy

Everything useful derives from std::exception, so one handler can be a safety net.

std::exception
 +-- std::logic_error          -- a bug in the calling code
 |    +-- std::invalid_argument
 |    +-- std::domain_error
 |    +-- std::length_error
 |    +-- std::out_of_range
 +-- std::runtime_error        -- something the code could not have prevented
 |    +-- std::range_error
 |    +-- std::overflow_error
 |    +-- std::system_error
 +-- std::bad_alloc            -- allocation failed

The logic_error / runtime_error split is a useful discipline: logic_error means "the caller passed something impossible — fix the code", runtime_error means "the world did not cooperate".

Catch by const reference, always

catch (std::exception e)         // WRONG: copies, and SLICES a derived exception
catch (const std::exception& e)  // right

Catching by value slices, so a std::out_of_range caught as std::exception loses its identity and its message may too. Catching by reference costs nothing and preserves the dynamic type.

Handler order matters

Handlers are tried in order, and the first one that can accept the exception wins — there is no best-match ranking as with overloads.

try { risky(); }
catch (const std::exception& e) { }         // catches EVERYTHING first
catch (const std::out_of_range& e) { }      // unreachable -- compiler warns

Stack unwinding is what makes it safe

void middle() {
    std::string buffer(1000, 'x');          // destructor WILL run
    std::ofstream log("out.txt");           // file WILL be closed
    throw std::runtime_error("failed");
}                                           // both destroyed during unwinding

Every fully-constructed local between the throw and the catch is destroyed, in reverse order. Raw resources are the exception to this guarantee:

void leaky() {
    int* data = new int[1000];
    mayThrow();                             // if it throws, 'data' leaks
    delete[] data;                          // never reached
}

void safe() {
    std::vector<int> data(1000);            // destructor cleans up regardless
    mayThrow();
}

This is the strongest practical argument for RAII: with new/delete and raw handles, every throw is a potential leak, and there is no way to plug them all by hand.

Custom exception types

Derive from std::runtime_error and you get what() for free.

class ConfigError : public std::runtime_error {
    std::string key;
public:
    ConfigError(const std::string& missingKey)
        : std::runtime_error("missing configuration key: " + missingKey),
          key(missingKey) {}

    const std::string& missingKey() const { return key; }
};

try { loadConfig(); }
catch (const ConfigError& e) {
    std::cout << e.what() << " (key: " << e.missingKey() << ")\n";
}

A custom type lets callers catch your failures specifically, and carry structured data alongside the message.

Rethrowing

A bare throw; inside a handler resends the current exception unchanged, preserving its dynamic type:

try { work(); }
catch (const std::exception& e) {
    log(e.what());
    throw;                      // pass it on; 'throw e;' would slice it
}

noexcept

noexcept promises a function will not throw. Break the promise and the program calls std::terminate — there is no recovery.

void cleanup() noexcept;                    // a promise, enforced brutally

Destructors are implicitly noexcept, which means a destructor must never let an exception escape. If one does during unwinding, the program terminates. Wrap risky destructor work in try { ... } catch (...) { }. Move constructors marked noexcept also let std::vector use a faster reallocation path, so it is worth adding where it is true.

The exception-safety levels

LevelGuarantee
No guaranteeAnything may be broken; avoid
BasicNo leaks, object still valid but state unspecified
StrongEither it fully succeeded, or nothing changed
noexceptCannot fail

The strong guarantee is usually achieved by doing the risky work on a copy and swapping at the end, since swapping does not throw.

Cost

Entering a try block costs essentially nothing on modern compilers — the "zero-cost" model puts all the work in tables consulted only when a throw happens. Throwing, by contrast, is slow: hundreds of nanoseconds to microseconds. That asymmetry is the design guidance. Use exceptions on paths that should almost never execute; do not use them for control flow in a loop.

Exceptions versus return values

SituationPrefer
The caller can reasonably expect this to happenReturn value / std::optional
The failure is a programming bugthrow a logic_error (or assert)
The environment failed and there is nothing local to dothrow a runtime_error
A constructor cannot build a valid objectthrow — there is no return value
Failure must be reported across a C API boundaryError code

Constructors deserve special mention: they have no return channel, so throwing is the only way to refuse to build an invalid object.

Uncaught exceptions

An exception with no matching handler calls std::terminate, which aborts. Any main that can throw should have a top-level try:

int main() {
    try {
        run();
        return 0;
    }
    catch (const std::exception& e) {
        std::cerr << "fatal: " << e.what() << "\n";
        return 1;
    }
    catch (...) {                   // last resort: something not derived from std::exception
        std::cerr << "fatal: unknown error\n";
        return 2;
    }
}

Real World Example: A Config-Driven Job Runner

Startup failures throw; per-item failures do not. That division is the whole design.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <stdexcept>
#include <system_error>
#include <sstream>

// --- A custom hierarchy, so callers can be as specific as they need.
class ConfigError : public std::runtime_error {
public:
    explicit ConfigError(const std::string& what)
        : std::runtime_error("config: " + what) {}
};

class MissingKey : public ConfigError {
    std::string key;
public:
    explicit MissingKey(std::string k)
        : ConfigError("missing key '" + k + "'"), key(std::move(k)) {}
    const std::string& which() const { return key; }
};

class BadValue : public ConfigError {
public:
    BadValue(const std::string& key, const std::string& value)
        : ConfigError("key '" + key + "' has bad value '" + value + "'") {}
};

class Config {
    std::map<std::string, std::string> values;
public:
    void set(std::string key, std::string value) {
        values[std::move(key)] = std::move(value);
    }

    // The program cannot run without this -> throw.
    const std::string& require(const std::string& key) const {
        const auto it = values.find(key);
        if (it == values.end()) { throw MissingKey(key); }
        return it->second;
    }

    int requireInt(const std::string& key) const {
        const std::string& text = require(key);
        std::istringstream in(text);
        int n = 0;
        if (!(in >> n)) { throw BadValue(key, text); }
        return n;
    }

    // Optional settings are NOT exceptional -> return an optional.
    std::optional<std::string> optional(const std::string& key) const {
        const auto it = values.find(key);
        if (it == values.end()) { return std::nullopt; }
        return it->second;
    }
};

// RAII: guarantees the "finished" message even if the body throws.
class JobScope {
    std::string name;
    bool failed{false};
public:
    explicit JobScope(std::string jobName) : name(std::move(jobName)) {
        std::cout << "  start " << name << "\n";
    }
    void markFailed() { failed = true; }
    ~JobScope() {                                   // must never throw
        std::cout << "  end   " << name
                  << (failed ? " (failed)" : " (ok)") << "\n";
    }
};

struct JobOutcome { int done; int failed; };

// Per-item failure is expected, so it is caught HERE and the batch continues.
JobOutcome runJobs(const std::vector<std::string>& jobs, int retryLimit) {
    JobOutcome outcome{0, 0};
    for (const std::string& job : jobs) {
        JobScope scope{job};
        try {
            if (job == "corrupt") {
                throw std::runtime_error("checksum mismatch");
            }
            if (job == "timeout") {
                throw std::system_error(std::make_error_code(
                    std::errc::timed_out), "upstream");
            }
            ++outcome.done;
        }
        catch (const std::system_error& e) {         // most specific first
            std::cout << "    retryable (" << retryLimit << " left): "
                      << e.what() << "\n";
            scope.markFailed();
            ++outcome.failed;
        }
        catch (const std::exception& e) {
            std::cout << "    permanent: " << e.what() << "\n";
            scope.markFailed();
            ++outcome.failed;
        }
        // scope's destructor runs here either way
    }
    return outcome;
}

void run(const Config& cfg) {
    const std::string& queue = cfg.require("queue");          // may throw
    const int retries = cfg.requireInt("retries");            // may throw

    // Absent is fine, so no exception involved.
    const std::string label = cfg.optional("label").value_or("(unlabelled)");

    std::cout << "queue=" << queue << " retries=" << retries
              << " label=" << label << "\n";

    const JobOutcome result = runJobs({"import", "corrupt", "timeout", "export"},
                                      retries);
    std::cout << result.done << " done, " << result.failed << " failed\n";
}

int main() {
    Config good;
    good.set("queue", "nightly");
    good.set("retries", "3");

    try {
        run(good);
    }
    catch (const std::exception& e) {
        std::cerr << "fatal: " << e.what() << "\n";
        return 1;
    }

    std::cout << "--- now with a broken config ---\n";
    Config broken;
    broken.set("queue", "nightly");
    broken.set("retries", "three");           // not a number

    try {
        run(broken);
    }
    catch (const MissingKey& e) {
        std::cerr << "fatal, add this key: " << e.which() << "\n";
        return 1;
    }
    catch (const ConfigError& e) {
        std::cerr << "fatal: " << e.what() << "\n";
        return 1;
    }
    catch (...) {
        std::cerr << "fatal: unknown\n";
        return 2;
    }
    return 0;
}

The line between throwing and returning is drawn on one question: can the program carry on? require and requireInt throw because a job runner with no queue name has nothing to do — there is no sensible default and no useful partial result — whereas optional returns std::optional<std::string> because an absent label is an ordinary, expected state, and throwing there would force callers to write a try block around a non-problem. The custom hierarchy MissingKey and BadValue under ConfigError under std::runtime_error means main can choose its precision: it catches MissingKey specifically to print the actionable "add this key", falls back to ConfigError, and keeps catch (...) as a last resort — and the handlers are ordered most-specific-first, because reversing the first two would make the MissingKey branch dead code. runJobs catches inside its loop rather than letting failures propagate, which is what allows a corrupt item to be recorded and the remaining jobs to run; catching outside the loop would abandon the batch at the first bad record. JobScope is the RAII half of the story: its destructor prints the closing line whether the body succeeded, threw, or was skipped, and that destructor deliberately contains nothing that could throw, since an exception escaping a destructor during unwinding terminates the program. Every handler takes const&, so a std::system_error caught as std::exception would still report its real message rather than a sliced copy — and note that throw; rather than throw e; would be required if any of these wanted to pass the exception onward intact.


Common Mistakes

  1. Catching by value. catch (std::exception e) slices the exception and loses its type and often its message.
  2. Ordering handlers general-to-specific. The base handler catches everything and the specific ones are unreachable.
  3. Using exceptions for ordinary control flow. Throwing per loop iteration is orders of magnitude slower than a branch.
  4. Letting an exception escape a destructor. During unwinding this calls std::terminate immediately.
  5. Raw new between a throw and its handler. The memory leaks; unwinding only runs destructors.
  6. throw e; when rethrowing. It slices the exception; use a bare throw;.
  7. Swallowing exceptions with an empty catch (...) { }. The failure vanishes and the bug surfaces somewhere unrelated.
  8. Throwing something that is not derived from std::exception, such as an int or a string literal, so no generic handler can report it.
  9. Marking a function noexcept that can throw. The program terminates rather than propagating.
  10. No top-level handler in main, turning any escaped exception into a bare crash.
  11. Returning a value from a constructor to signal failure. Constructors have no return; throw instead.

Best Practices

  • Throw for the exceptional, return for the expected. std::optional covers most "might not be there" cases.
  • Always catch (const T&), and order handlers most specific first.
  • Derive custom exceptions from std::runtime_error so what() and generic handlers work.
  • Carry structured data on the exception, not just a formatted string, when the caller may need to act on it.
  • Use RAII for every resource. It is what makes unwinding safe, and it removes the need for catch blocks that only clean up.
  • Keep destructors noexcept; swallow anything risky inside them.
  • Catch at the level that can actually do something — per item for retryable work, at main for fatal errors.
  • Rethrow with a bare throw;.
  • Mark genuinely non-throwing functions noexcept, especially move constructors.
  • Give main a top-level try with an std::exception handler and a catch (...) fallback.

Practice Exercises

  1. Slice it: Write a function throwing std::out_of_range, catch it once as std::exception e by value and once as const std::exception& e, and print what() in both. Record the difference, then explain in a comment which type information was lost.
  2. Prove the leak: Write void leaky() that allocates with new int[1000], calls something that throws, then deletes. Run it under g++ -fsanitize=address and paste the leak report. Rewrite it with std::vector<int> and confirm the report is clean.
  3. Your own hierarchy: Write ValidationError deriving from std::runtime_error and carrying the offending field name, plus a validate function that throws it. Catch it specifically to print the field, and catch std::exception as a fallback. Then swap the two handlers' order and record the compiler's warning.