Chapter 32 of 48

Exception Handling

Programs fail in ways that are not bugs in the program itself: a file does not exist, the user types letters where a number was expected, the network drops, memory runs out, a bank account does not have enough money. A good program must detect such problems and respond to them sensibly instead of crashing or silently producing garbage.

In C, the usual approach is to return an error code (like -1 or NULL) and hope the caller checks it. C++ adds a more powerful mechanism called exception handling. In this chapter we will learn throw, try and catch, what happens to objects when an exception flies past them (stack unwinding), the standard exception classes, how to write our own, noexcept, exception-safety guarantees, and the modern C++23 alternative std::expected.


Why Not Just Return Error Codes?

Consider a function that divides two numbers. With error codes, what should it return when the divisor is zero? Every double value is a possible valid answer, so there is no "spare" value to signal an error. Error codes have other problems too:

  • They are easy to ignore. Nothing forces the caller to check the return value.

  • They clutter the code. Every call needs an if after it, and each function in a chain of calls must pass the error upward by hand.

  • Constructors and operators cannot return them. A constructor has no return value at all, so how does it report "could not open the file"?

Exceptions solve these problems by separating the code that detects an error from the code that handles it, possibly many function calls away.


The Three Keywords

An exception is an object that a function throws to signal that it cannot do its job. throw raises it, try marks a block of code whose exceptions we want to handle, and catch defines a handler for exceptions of a particular type.

try {
    // code that might throw
}
catch (const SomeType& e) {
    // runs only if a SomeType (or derived) exception was thrown
}

Your First Exception

#include <iostream>
#include <stdexcept>

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

int main() {
    try {
        std::cout << divide(10, 4) << '\n';
        std::cout << divide(1, 0) << '\n';   // throws
        std::cout << "This line is skipped\n";
    }
    catch (const std::invalid_argument& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
    std::cout << "Program continues\n";
}

Output:

2.5
Error: division by zero
Program continues

Let us trace exactly what happened:

  1. divide(10, 4) returns normally and 2.5 is printed.

  2. divide(1, 0) executes throw. An exception object of type std::invalid_argument is created, and the function stops immediately — it does not return a value.

  3. The rest of the try block is skipped (the "skipped" line never prints).

  4. C++ looks at the catch blocks after the try, finds one whose type matches, and runs it. e.what() returns the message we passed when throwing.

  5. After the catch block finishes, execution continues after the whole try-catch. The program does not go back to the point of the throw.

This last point is important: C++ uses the termination model. Once thrown, the failed operation is abandoned; you cannot "resume" it.


What Can Be Thrown?

You can throw an object of almost any type: an int, a std::string, a class object. In real code you should throw objects of classes derived from std::exception, but to understand matching, let us throw several types:

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

void process(int code) {
    if (code == 1) throw 42;                              // an int
    if (code == 2) throw std::string("bad input");        // a std::string
    if (code == 3) throw std::out_of_range("index 7");    // a standard exception
    if (code == 4) throw 3.14;                            // a double
    std::cout << "code " << code << " processed\n";
}

int main() {
    for (int code = 0; code <= 4; ++code) {
        try {
            process(code);
        }
        catch (int n) {
            std::cout << "caught int: " << n << '\n';
        }
        catch (const std::string& s) {
            std::cout << "caught string: " << s << '\n';
        }
        catch (const std::exception& e) {
            std::cout << "caught std::exception: " << e.what() << '\n';
        }
        catch (...) {
            std::cout << "caught something unknown\n";
        }
    }
}

Output:

code 0 processed
caught int: 42
caught string: bad input
caught std::exception: index 7
caught something unknown

How a catch block is chosen

  • Handlers are tried in order, top to bottom, and the first one that matches wins. It is not "best match" like function overloading.

  • A handler matches if its type is the same as the thrown type, or a public base class of it (this is why std::exception& caught the std::out_of_range). Pointer handlers also accept the usual derived-to-base pointer conversions.

  • Ordinary conversions do not apply: a thrown int is not caught by catch (double), and a thrown "text" (a const char*) is not caught by catch (const std::string&).

  • catch (...) (three dots) catches anything. It must be the last handler; otherwise the handlers after it could never run (the compiler gives an error).

Because of first-match ordering, always put derived exception types before their base types. If catch (const std::exception&) came first, a more specific handler below it would never be reached (GCC warns about this).

What If Nobody Catches It?

#include <iostream>
#include <stdexcept>

int main() {
    std::cout << "before" << std::endl;
    throw std::runtime_error("nobody catches me");
    std::cout << "after\n";
}

Output (GCC on Linux; the program is then aborted):

before
terminate called after throwing an instance of 'std::runtime_error'
  what():  nobody catches me

If an exception leaves main() without being caught, the program calls std::terminate(), which by default calls std::abort(). Whether local objects are destroyed before this happens is implementation-defined, so do not rely on destructors running in that case. (We used std::endl here on purpose so that "before" is flushed before the abort.)


Stack Unwinding

When an exception is thrown deep inside nested function calls, C++ walks back up the call stack looking for a matching handler. As it leaves each function, it destroys all fully-constructed local objects in that function, in reverse order of construction. This process is called stack unwinding.

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

class Tracer {
    std::string name;
public:
    explicit Tracer(const std::string& n) : name(n) {
        std::cout << "  construct " << name << '\n';
    }
    ~Tracer() { std::cout << "  destroy   " << name << '\n'; }
};

void level3() {
    Tracer t("t3");
    std::cout << "  level3 throws\n";
    throw std::runtime_error("disk full");
}

void level2() {
    Tracer t("t2");
    level3();
    std::cout << "  never printed\n";
}

void level1() {
    Tracer t("t1");
    level2();
}

int main() {
    try {
        level1();
    }
    catch (const std::exception& e) {
        std::cout << "caught in main: " << e.what() << '\n';
    }
}

Output:

  construct t1
  construct t2
  construct t3
  level3 throws
  destroy   t3
  destroy   t2
  destroy   t1
caught in main: disk full

Picture the call stack at the moment of the throw:

   main()      try { ... }  catch (const std::exception&)   <-- handler found here
     |
   level1()    Tracer t1                 destroyed 3rd
     |
   level2()    Tracer t2                 destroyed 2nd
     |
   level3()    Tracer t3                 destroyed 1st
               throw runtime_error  ---- search goes UP the stack ----^

Every destructor ran, even though level1() and level2() never reached their normal end. This is the foundation of RAII (Resource Acquisition Is Initialization), which you met in Constructors & Destructors: if a resource (memory, a file, a lock) is owned by an object whose destructor releases it, the resource is released automatically whether the function exits normally or by an exception.

Raw pointers do not get this protection:

void leaky() {
    int* data = new int[1000];
    mightThrow();          // if this throws...
    delete[] data;         // ...this line never runs: memory leak!
}

A pointer is not an object with a destructor that frees memory, so unwinding does nothing for it. The fix is to let an object own the memory — for example a std::vector<int> data(1000);, or a smart pointer (covered in the Smart Pointers chapter).


The Standard Exception Hierarchy

The standard library defines a family of exception classes, all derived from std::exception (header <exception>; most of the others are in <stdexcept>). Every one of them has a virtual function what() that returns a C-string message.

std::exception
 ├── std::logic_error            (bugs that could have been prevented by checking)
 │    ├── std::invalid_argument
 │    ├── std::domain_error
 │    ├── std::length_error
 │    └── std::out_of_range
 ├── std::runtime_error          (problems detectable only at run time)
 │    ├── std::range_error
 │    ├── std::overflow_error
 │    ├── std::underflow_error
 │    └── std::system_error       (→ std::ios_base::failure, std::filesystem::filesystem_error)
 ├── std::bad_alloc              (new could not allocate memory)
 │    └── std::bad_array_new_length
 ├── std::bad_cast               (failed dynamic_cast to a reference)
 ├── std::bad_typeid
 ├── std::bad_function_call
 ├── std::bad_optional_access    (C++17)
 ├── std::bad_variant_access     (C++17)
 └── std::bad_expected_access    (C++23)

Some common sources:

Operation

Exception thrown on failure

vector::at(i), string::at(i) with a bad index

std::out_of_range

std::stoi("abc")

std::invalid_argument

std::stoi("99999999999")

std::out_of_range

new when memory is exhausted

std::bad_alloc

vector::reserve(n) with n > max_size()

std::length_error

dynamic_cast<Derived&>(baseRef) on the wrong type

std::bad_cast

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

int main() {
    std::vector<int> v = {10, 20, 30};
    try {
        std::cout << v.at(1) << '\n';
        std::cout << v.at(10) << '\n';     // bounds-checked: throws
    }
    catch (const std::out_of_range& e) {
        std::cout << "out_of_range: " << e.what() << '\n';
    }
}

Output (GCC's libstdc++):

20
out_of_range: vector::_M_range_check: __n (which is 10) >= this->size() (which is 3)

The exact text returned by what() for library exceptions is not specified by the standard; other compilers print different messages. Only rely on the exception's type.


Writing Your Own Exception Classes

For errors specific to your program, derive a class from one of the standard ones — usually std::runtime_error or std::logic_error. You get what() for free, and callers who catch std::exception& will still catch your type.

#include <iostream>
#include <stdexcept>

class InsufficientFunds : public std::runtime_error {
    double needed;
public:
    InsufficientFunds(double balance, double amount)
        : std::runtime_error("insufficient funds"),
          needed(amount - balance) {}

    double shortfall() const { return needed; }
};

class Account {
    double balance;
public:
    explicit Account(double b) : balance(b) {}

    void withdraw(double amount) {
        if (amount <= 0)
            throw std::invalid_argument("amount must be positive");
        if (amount > balance)
            throw InsufficientFunds(balance, amount);
        balance -= amount;
    }
    double getBalance() const { return balance; }
};

int main() {
    Account acc(500);
    double requests[] = { 200, -5, 800 };

    for (double amt : requests) {
        try {
            acc.withdraw(amt);
            std::cout << "Withdrew " << amt << ", balance " << acc.getBalance() << '\n';
        }
        catch (const InsufficientFunds& e) {           // most specific first
            std::cout << e.what() << ": short by " << e.shortfall() << '\n';
        }
        catch (const std::exception& e) {              // anything else standard
            std::cout << "Error: " << e.what() << '\n';
        }
    }
}

Output:

Withdrew 200, balance 300
Error: amount must be positive
insufficient funds: short by 500

The custom class carries extra information (shortfall()), which a plain error code could not. Notice the handler order: the specific InsufficientFunds first, the general std::exception after it. Also notice that the account balance was not changed by the failed withdrawals — the checks happen before modifying anything.


Catch by Reference, Rethrow with throw;

Two small rules prevent two classic bugs.

#include <iostream>
#include <stdexcept>

void byValue() {
    try {
        throw std::out_of_range("index 10");
    }
    catch (std::exception e) {            // caught BY VALUE: sliced!
        std::cout << "byValue sees: " << e.what() << '\n';
    }
}

void rethrowCopy() {
    try {
        throw std::out_of_range("index 10");
    }
    catch (std::exception& e) {
        throw e;                          // throws a NEW std::exception (sliced copy)
    }
}

void rethrowSame() {
    try {
        throw std::out_of_range("index 10");
    }
    catch (std::exception& e) {
        std::cout << "logging: " << e.what() << '\n';
        throw;                            // rethrows the ORIGINAL out_of_range
    }
}

int main() {
    byValue();

    try { rethrowCopy(); }
    catch (const std::out_of_range&) { std::cout << "copy: still out_of_range\n"; }
    catch (const std::exception&)    { std::cout << "copy: became plain std::exception\n"; }

    try { rethrowSame(); }
    catch (const std::out_of_range&) { std::cout << "same: still out_of_range\n"; }
    catch (const std::exception&)    { std::cout << "same: became plain std::exception\n"; }
}

Output:

byValue sees: std::exception
copy: became plain std::exception
logging: index 10
same: still out_of_range
  • Catching by value slices the object. catch (std::exception e) copies only the std::exception part of the out_of_range, so what() no longer returns our message (libstdc++ prints the class name instead). GCC warns: catching polymorphic type ‘class std::exception’ by value [-Wcatch-value=]. Always catch by reference, preferably const&.

  • throw e; throws a copy of the static type, here a plain std::exception, losing the real type. A bare throw; inside a handler rethrows the original exception object unchanged. Use it when you want to log an error and let a higher level deal with it.

(Throwing pointers like throw new MyError; is also a bad idea: someone must remember to delete it. Throw by value, catch by reference.)


Exceptions in Constructors and Destructors

Constructors

Throwing from a constructor is the correct way to report that an object could not be created. The rule is: an object whose constructor did not finish never existed, so its destructor is not called. However, members and base classes that were already fully constructed are destroyed.

#include <iostream>
#include <stdexcept>

struct Part {
    const char* name;
    explicit Part(const char* n) : name(n) { std::cout << "  Part " << name << " built\n"; }
    ~Part() { std::cout << "  Part " << name << " destroyed\n"; }
};

class Machine {
    Part engine{"engine"};
    Part wheels{"wheels"};
public:
    Machine() {
        std::cout << "  Machine constructor body\n";
        throw std::runtime_error("calibration failed");
    }
    ~Machine() { std::cout << "  ~Machine\n"; }   // never runs here
};

int main() {
    try {
        Machine m;
    }
    catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << '\n';
    }
}

Output:

  Part engine built
  Part wheels built
  Machine constructor body
  Part wheels destroyed
  Part engine destroyed
caught: calibration failed

The two Part members were cleaned up (in reverse order), but ~Machine() was never called. That is why a constructor that grabs a raw resource with new and then throws will leak: put each resource into its own RAII member instead.

Destructors

Since C++11, destructors are implicitly noexcept (unless you explicitly write noexcept(false), or a member or base class has such a destructor). So if an exception escapes an ordinary destructor, std::terminate() is called. Even before C++11, throwing from a destructor during stack unwinding (while another exception is in flight) terminated the program. Rule: never let exceptions escape destructors. Catch and handle (or log) them inside.


The noexcept Specifier (C++11)

Writing noexcept after a function's parameter list is a promise: "this function will never throw". The compiler and the standard library can use that promise for optimisation — for example, containers prefer to move elements during reallocation only when the move constructor is noexcept (more on that in Move Semantics & Rvalue References).

There is also a compile-time noexcept operator that asks whether an expression is declared not to throw:

#include <iostream>

void safe() noexcept { }
void risky() { }
void alsoSafe() noexcept(true) { }
void mayThrow() noexcept(false) { }

int main() {
    std::cout << std::boolalpha;
    std::cout << "safe:     " << noexcept(safe()) << '\n';
    std::cout << "risky:    " << noexcept(risky()) << '\n';
    std::cout << "alsoSafe: " << noexcept(alsoSafe()) << '\n';
    std::cout << "mayThrow: " << noexcept(mayThrow()) << '\n';
    std::cout << "1 + 2:    " << noexcept(1 + 2) << '\n';
}

Output:

safe:     true
risky:    false
alsoSafe: true
mayThrow: false
1 + 2:    true

What if a noexcept function throws anyway? The exception cannot leave the function: std::terminate() is called immediately, and no outer catch gets a chance.

#include <iostream>
#include <stdexcept>

void promise() noexcept {
    throw std::runtime_error("oops");   // breaks the promise
}

int main() {
    try {
        promise();
    }
    catch (...) {
        std::cout << "never reached\n";
    }
}

GCC warns at compile time (‘throw’ will always call ‘terminate’ [-Wterminate]), and at run time the output is:

terminate called after throwing an instance of 'std::runtime_error'
  what():  oops

Note: the old dynamic exception specifications such as void f() throw(int); were deprecated in C++11 and removed in C++17, and throw() was removed in C++20. If you see them in old textbooks, use noexcept instead.


Exception Safety Guarantees

When an operation fails with an exception, what state are your objects left in? Library designers describe this with four levels (from best to worst):

Guarantee

Promise

Example

No-throw

The operation never throws

Destructors, swap, vector::size()

Strong

If it throws, the state is exactly as before ("commit or rollback")

vector::push_back (if the element's copy/move gives this guarantee); our withdraw()

Basic

If it throws, no resources leak and objects are still valid, but their values may have changed

Most container operations in general

None

Anything may happen: leaks, corrupted objects

Code with raw new/delete and no RAII

A simple technique to get the strong guarantee: do all the work that might throw first, on the side, and only then modify the real object with operations that cannot throw.


A Modern Alternative: std::expected (C++23)

Exceptions are great for rare, truly exceptional failures. But for errors that are an expected part of normal flow — like parsing user input — many programmers prefer to return the error as a value. C++23 added std::expected<T, E> (header <expected>), which holds either a value of type T or an error of type E.

#include <iostream>
#include <expected>
#include <string>

std::expected<int, std::string> parseAge(const std::string& s) {
    if (s.empty())
        return std::unexpected("empty input");
    int age = 0;
    for (char c : s) {
        if (c < '0' || c > '9')
            return std::unexpected("not a number: " + s);
        age = age * 10 + (c - '0');
        if (age > 150)
            return std::unexpected("unrealistic age");
    }
    return age;
}

int main() {
    std::string inputs[] = {"21", "abc", "", "999"};
    for (const std::string& input : inputs) {
        auto result = parseAge(input);
        if (result)
            std::cout << "age = " << *result << '\n';
        else
            std::cout << "error: " << result.error() << '\n';
    }
}

Output:

age = 21
error: not a number: abc
error: empty input
error: unrealistic age

The result converts to true if it holds a value; *result gives the value and result.error() gives the error. Unlike an error code, the type itself reminds the caller that failure is possible. (This program needs -std=c++23; GCC 12 or newer.)

Approach

Can be ignored silently?

Works in constructors?

Cost when no error

Best for

Error codes

Yes

No

Tiny

C APIs, very low-level code

Exceptions

No (uncaught → terminate)

Yes

Usually near zero; throwing is expensive

Rare failures, constructor failures, errors far from the handler

std::expected

Harder (you must unwrap it)

No

Small

Frequent, expected failures handled by the direct caller

With the common "table-based" implementation used by GCC and Clang, a try block costs essentially nothing when no exception is thrown, but actually throwing is relatively slow (often microseconds). So do not use exceptions for normal control flow, like ending a loop.


Common Mistakes

  • Catching by value — slices derived exceptions. Use const&.

  • Wrong handler order — base-class handler before derived-class handler makes the derived one unreachable.

  • catch (...) not last — compile error.

  • throw e; instead of throw; — loses the original dynamic type.

  • Throwing from a destructor — calls std::terminate().

  • Using raw new without RAII — memory leaks when an exception passes by.

  • Swallowing errors with an empty catch (...) {} — the program continues in a broken state and the bug is hidden.

  • Expecting catch (double) to catch a thrown int — no arithmetic conversions in handler matching.


Interview / GATE-Style Questions

Q1. What is stack unwinding?

When an exception propagates out of a scope, C++ destroys all fully-constructed automatic (local) objects of that scope in reverse order of construction, moving up the call stack until a matching handler is found. This guarantees destructors run, which makes RAII-based cleanup work.

Q2. What does this print?
try { throw 5; } catch (double d) { cout << "double"; } catch (...) { cout << "other"; }

other. A thrown int does not match catch (double) because no arithmetic conversion is performed when matching handlers.

Q3. Why should exceptions be caught by reference?

To avoid slicing (copying only the base part of a derived exception, losing its data and its overridden what()) and to avoid an extra copy. A const& handler also preserves polymorphic behaviour.

Q4. If a constructor throws, is the destructor called?

No, not for the object being constructed, because its lifetime never began. But its already-constructed members and base-class subobjects are destroyed.

Q5. Difference between throw; and throw e; inside a catch block?

throw; rethrows the current exception object itself, keeping its dynamic type. throw e; copy-initialises a new exception from e's static type, which may slice a derived exception into a base one.

Q6. What happens if a noexcept function throws?

std::terminate() is called; the exception does not propagate to any caller's handler. (Whether the stack is unwound before that is implementation-defined.)

Q7. Name the exception thrown by new on failure and how to get a null pointer instead.

std::bad_alloc. Using new (std::nothrow) T (from <new>) returns nullptr instead of throwing.


Summary

  • throw raises an exception; try marks code to watch; catch handles exceptions of a given type. After a handler runs, execution continues after the try-catch.

  • Handlers are checked in order; the first match wins. Derived-to-base matches, arithmetic conversions do not. catch (...) goes last.

  • An uncaught exception calls std::terminate().

  • Stack unwinding destroys local objects as an exception propagates — use RAII so cleanup happens automatically.

  • Prefer standard exceptions or classes derived from std::runtime_error/std::logic_error. Throw by value, catch by const&, rethrow with throw;.

  • Throw from constructors to signal failure; never let exceptions escape destructors (they are noexcept by default).

  • noexcept (C++11) promises no exceptions; breaking the promise terminates the program.

  • Know the four exception-safety levels: no-throw, strong, basic, none.

  • For expected, frequent failures, C++23's std::expected is a clean alternative.