# Exception Handling in C++ — try, catch, throw, Stack Unwinding and Custom Exceptions

Source: https://skills101.in/learn/cpp/cpp-exception-handling — Skills101 free tutorial (C++ Programming). Updated 2026-11-21.

Programs meet problems they cannot fix on the spot: a file that does not exist, a withdrawal larger than the balance, text where a number was expected. The function that **finds** the problem is often not the function that knows what to **do** about it. **Exceptions** carry the error from the place it happens to a place that can handle it. The memory lesson showed a first `try`/`catch`; this lesson covers the full picture that exams and interviews ask about.

## 1. Why not just return an error code?

In C, functions report errors with return values like `-1` or `NULL`. That has three problems:

1. The caller can **forget to check** the value, and the program carries on with bad data.
2. Every function in the chain must check and pass the code upwards, which clutters the code.
3. Some functions have no spare return value — a constructor returns nothing at all.

An exception cannot be silently ignored: if nobody catches it, the program stops. And the functions in between need no extra code at all.

## 2. try, throw and catch

- `throw` creates an exception object and starts looking for a handler.
- `try { ... }` marks code whose exceptions you want to handle.
- `catch (Type &e) { ... }` handles exceptions of that type. A `try` can have several `catch` blocks; the **first one that matches** runs.

```cpp
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int parse_marks(const string &s) {
    int m = stoi(s);                       // throws invalid_argument for "abc"
    if (m < 0 || m > 100) throw out_of_range("marks must be 0-100");
    return m;
}

int main() {
    for (string s : {"87", "abc", "140"}) {
        try {
            cout << parse_marks(s) << "\n";
        } catch (const invalid_argument &) {
            cout << "not a number: " << s << "\n";
        } catch (const out_of_range &e) {
            cout << e.what() << "\n";
        }
    }
    cout << "done\n";
    return 0;
}
```

```text
87
not a number: abc
marks must be 0-100
done
```

When `throw` runs, the rest of the `try` block is skipped. After a matching `catch` finishes, the program continues **after** the whole try/catch, so the loop goes on to the next string.

Always **catch by const reference** (`const T &`). Catching by value makes a copy, and if you catch a derived exception through a base class by value, the extra parts are sliced off.

## 3. The standard exception classes

The standard library throws objects from a family of classes rooted at `std::exception`. Each has a `what()` function that returns the message.

![Tree of standard exceptions: std::exception at the top, logic_error with invalid_argument and out_of_range below it, runtime_error with overflow_error, and bad_alloc for failed new](https://skills101.in/learn-img/cpp/exception-hierarchy.svg)

| Exception | Header | Thrown by / used for |
|---|---|---|
| `invalid_argument` | `<stdexcept>` | `stoi("abc")`, bad input values |
| `out_of_range` | `<stdexcept>` | `vector::at`, `string::at`, `stoi` of a huge number |
| `runtime_error` | `<stdexcept>` | errors only detectable while running (file, network) |
| `bad_alloc` | `<new>` | `new` cannot get memory |
| `bad_cast` | `<typeinfo>` | failed `dynamic_cast` to a reference |

Because they form a hierarchy, `catch (const exception &e)` catches all of them. **Order matters:** put specific (derived) types first and general (base) types last. If `catch (const exception &)` comes first, it matches everything, and the later blocks can never run. Finally, `catch (...)` catches anything at all, even an `int` that was thrown.

## 4. Stack unwinding: destructors still run

When an exception leaves a function, C++ **unwinds the stack**: it exits each function between the `throw` and the matching `catch`, and destroys every local object in those functions, calling their destructors in reverse order of creation.

```cpp
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

struct Guard {
    string name;
    Guard(string n) : name(n) { cout << "open " << name << "\n"; }
    ~Guard() { cout << "close " << name << "\n"; }
};

void write_report() {
    Guard g("file");
    throw runtime_error("disk full");
    cout << "never printed\n";
}

void save_all() {
    Guard g("connection");
    write_report();
    cout << "never printed\n";
}

int main() {
    try {
        save_all();
    } catch (const exception &e) {
        cout << "caught: " << e.what() << "\n";
    }
    return 0;
}
```

```text
open connection
open file
close file
close connection
caught: disk full
```

![Call stack during unwinding: main calls save_all, which calls write_report, which throws. write_report's file guard closes first, then save_all's connection guard, then main's catch block runs](https://skills101.in/learn-img/cpp/stack-unwinding.svg)

This is why **RAII** (Resource Acquisition Is Initialisation) and exceptions work so well together: if every resource — memory, a file, a lock — is owned by an object whose destructor releases it, then nothing leaks even when an error jumps out of the middle of a function. A raw `new` without a matching `delete` would leak here; a `unique_ptr` or `vector` would not.

## 5. Writing your own exception class

For errors that belong to your program, derive a class from a standard one, usually `runtime_error`. You get `what()` for free and can add extra data.

```cpp
#include <iostream>
#include <stdexcept>
using namespace std;

class InsufficientFunds : public runtime_error {
public:
    double shortBy;
    InsufficientFunds(double s) : runtime_error("insufficient funds"), shortBy(s) {}
};

class Account {
    double balance;
public:
    Account(double b) : balance(b) {}
    void withdraw(double amount) {
        if (amount <= 0) throw invalid_argument("amount must be positive");
        if (amount > balance) throw InsufficientFunds(amount - balance);
        balance -= amount;
    }
    double get() const { return balance; }
};

int main() {
    Account acc(500);
    double tries[] = {200, -5, 1000};
    for (double t : tries) {
        try {
            acc.withdraw(t);
            cout << "ok, balance " << acc.get() << "\n";
        } catch (const InsufficientFunds &e) {
            cout << e.what() << ", short by " << e.shortBy << "\n";
        } catch (const exception &e) {
            cout << "error: " << e.what() << "\n";
        }
    }
    return 0;
}
```

```text
ok, balance 300
error: amount must be positive
insufficient funds, short by 700
```

`InsufficientFunds` is caught first because it is listed first; the general `exception` block catches the `invalid_argument`.

## 6. Rethrowing with `throw;`

Sometimes a function wants to **do something** with an error (log it, clean up) but still let a caller decide what to do. Inside a `catch` block, a bare `throw;` rethrows the **same** exception object.

```cpp
#include <iostream>
#include <stdexcept>
using namespace std;

void upload() {
    try {
        throw runtime_error("network down");
    } catch (const exception &e) {
        cout << "log: " << e.what() << "\n";
        throw;                       // pass the same exception upwards
    }
}

int main() {
    try {
        upload();
    } catch (const runtime_error &e) {
        cout << "main handles: " << e.what() << "\n";
    }
    return 0;
}
```

```text
log: network down
main handles: network down
```

Write `throw;`, not `throw e;`. Here `e` is a `const exception &`, so `throw e;` would throw a new **copy of type `exception`**, losing the real type — `main`'s `catch (const runtime_error &)` would no longer match.

## 7. noexcept, constructors and destructors

- **`noexcept`** after a function's parameter list promises it will not throw. If an exception escapes it anyway, the program calls `std::terminate` and stops. Mark functions `noexcept` when they truly cannot fail, such as move constructors and simple getters.
- **Constructors** should throw when they cannot build a valid object (for example, a `Date` with month 13). There is no return value to report an error, so an exception is the right tool.
- **Destructors** must not throw. Destructors are `noexcept` by default, and they run during stack unwinding; an exception thrown then would end the program.

## Common mistakes

- Catching by value instead of by `const &`, which copies and can slice derived exceptions.
- Putting `catch (const exception &)` before more specific catch blocks — the specific ones never run.
- Throwing pointers (`throw new MyError`) — nobody knows who should delete it. Throw objects by value.
- Using `throw e;` to rethrow instead of `throw;`.
- Using exceptions for normal control flow, such as ending a loop. They are for unusual errors.
- Owning memory with raw `new` in code that can throw: the `delete` is skipped and memory leaks. Use RAII types.

## Quick recap

- `throw` raises, `try` watches, `catch` handles; the first matching catch runs.
- Catch by `const &`, most specific type first, `catch (...)` last if at all.
- Standard exceptions derive from `std::exception` and give a message through `what()`.
- Stack unwinding destroys all local objects on the way out, so RAII prevents leaks.
- Derive custom exceptions from `runtime_error` and add your own data.
- `throw;` rethrows the same object; `noexcept` promises no exceptions; destructors must not throw.


Practice quiz and free certificate: https://skills101.in/learn/cpp/cpp-exception-handling