C++ · Module 15 · Lesson 11 min read

try, throw & catch

The mechanism

c
try {
    risky_operation();            // may throw
} catch (const std::invalid_argument& e) {
    std::cerr << "Bad input: " << e.what() << '\n';
} catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << '\n';
}
arduino
void withdraw(double amount) {
    if (amount > balance_) throw std::runtime_error("insufficient funds");
    ...
}

What happens on throw

  1. The function stops immediately
  2. Stack unwinding: local objects in every exited scope are destroyed (destructors run → RAII cleanup ✅)
  3. Control jumps to the nearest matching catch
  4. If nothing catches it, std::terminate ends the program

Catching rules

  • Catch by const reference: catch (const std::exception& e) ✅ (no copying, no slicing)
  • Handlers are tried in order → put specific types before general ones
  • catch (...) catches anything (use as a last resort, e.g. in main or at thread boundaries)
  • throw; inside a catch rethrows the same exception

Standard exception hierarchy (<stdexcept>)

arduino
std::exception
├── std::logic_error         (bugs: should be preventable)
│   ├── std::invalid_argument
│   ├── std::domain_error
│   ├── std::length_error
│   └── std::out_of_range    (vector::at, string::at, map::at)
├── std::runtime_error       (things outside your control)
│   ├── std::range_error
│   ├── std::overflow_error
│   └── std::underflow_error
├── std::bad_alloc           (new failed)
├── std::bad_cast            (dynamic_cast to a reference)
└── std::bad_optional_access, std::bad_variant_access, std::bad_function_call …

e.what() returns the message.

Throw by value, catch by reference

throw std::runtime_error("...") — never throw new ... (who would delete it?).

When to use exceptions

✅ Errors the immediate caller can't reasonably handle: file missing deep in a loader, invalid constructor arguments, out of memory, broken invariants. ❌ Normal control flow ("not found" in a search) → return std::optional/bool instead.

Example

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

class Account {
public:
    explicit Account(double balance) {
        if (balance < 0) throw std::invalid_argument("opening balance cannot be negative");
        balance_ = balance;
    }
    void withdraw(double amount) {
        if (amount <= 0) throw std::invalid_argument("amount must be positive");
        if (amount > balance_) throw std::runtime_error("insufficient funds");
        balance_ -= amount;
    }
    double balance() const { return balance_; }
private:
    double balance_ = 0;
};

struct Step {
    std::string name;
    explicit Step(std::string n) : name(std::move(n)) { std::cout << "  enter " << name << '\n'; }
    ~Step() { std::cout << "  leave " << name << " (cleaned up)\n"; }
};

void level3() { Step s("level3"); throw std::runtime_error("network lost in level3"); }
void level2() { Step s("level2"); level3(); std::cout << "  never printed\n"; }

int main() {
    Account acc(1000);
    for (double amount : { 300.0, -5.0, 5000.0 }) {
        try {
            acc.withdraw(amount);
            std::cout << "withdrew " << amount << ", balance " << acc.balance() << '\n';
        } catch (const std::invalid_argument& e) {          // specific first
            std::cout << "invalid: " << e.what() << '\n';
        } catch (const std::exception& e) {                 // then general
            std::cout << "failed: " << e.what() << '\n';
        }
    }

    std::cout << "stack unwinding:\n";
    try {
        level2();
    } catch (const std::runtime_error& e) {
        std::cout << "caught in main: " << e.what() << '\n';
    }

    std::vector<int> v = { 1, 2, 3 };
    try {
        std::cout << v.at(10);
    } catch (const std::out_of_range& e) {
        std::cout << "out_of_range caught\n";
    }

    try {
        try {
            throw std::logic_error("inner problem");
        } catch (const std::exception& e) {
            std::cout << "logging: " << e.what() << ", rethrowing\n";
            throw;                                          // rethrow the same exception
        }
    } catch (...) {                                         // catch anything
        std::cout << "caught by catch(...)\n";
    }

    try {
        Account bad(-1);
    } catch (const std::invalid_argument& e) {
        std::cout << "constructor failed: " << e.what() << '\n';
    }
    return 0;
}

/* Output:
withdrew 300, balance 700
invalid: amount must be positive
failed: insufficient funds
stack unwinding:
  enter level2
  enter level3
  leave level3 (cleaned up)
  leave level2 (cleaned up)
caught in main: network lost in level3
out_of_range caught
logging: inner problem, rethrowing
caught by catch(...)
constructor failed: opening balance cannot be negative
*/