Skip to content

Module 7 · Templates, Exceptions, Namespaces and Files — topic 2 of 4

Exception Handling

Signal and handle errors with throw, try and catch. Learn standard exception types, catching by reference, rethrowing, custom exceptions, noexcept and exception safety.

Beginner 16 min read·Lesson 28 of 40 in C++ Programming

Learning objectives

  • Throw and catch exceptions by reference
  • Use the standard exception hierarchy and write custom exceptions
  • Understand stack unwinding and exception safety

Definition

Exception handling transfers control from a throw expression to the nearest matching catch handler up the call stack, destroying local objects along the way (stack unwinding).

Introduction

Error codes must be checked after every call, and constructors can't return them. Exceptions separate the normal path from error handling: the code that detects a problem throws, and a caller that can deal with it catches.

Why it matters

The standard library reports errors with exceptions (at, stoi, new), so every C++ programmer must handle them.

Combined with RAII, exceptions make error handling both concise and leak-free.

Detailed explanation

throw std::invalid_argument("message"); creates an exception object. try { ... } catch (const std::invalid_argument& e) { e.what(); } handles it.

Catch by const reference to avoid slicing and copies. Handlers are tried in order, so put derived types before base types; catch (...) catches anything.

Stack unwinding: as the exception propagates, destructors of all fully constructed local objects run — which is why RAII resources are released automatically.

Hierarchy: std::exception → std::logic_error (invalid_argument, out_of_range, domain_error) and std::runtime_error (overflow_error, range_error), plus std::bad_alloc.

noexcept declares that a function won't throw; if it does, std::terminate is called. Destructors and move operations should be noexcept.

Exception-safety levels: basic (no leaks, valid state), strong (operation either fully succeeds or has no effect), no-throw.

Syntax

C++
double safe_divide(double a, double b) {
if (b == 0) throw std::domain_error("division by zero");
return a / b;
}
try {
safe_divide(1, 0);
} catch (const std::domain_error& e) {
std::cerr << e.what() << '\n';
} catch (const std::exception& e) {
std::cerr << "other error: " << e.what() << '\n';
}
  • Include <stdexcept> for the standard exception classes.
  • throw; inside a handler rethrows the current exception.
  • Don't use exceptions for ordinary control flow.

Code examples

Catching a library exception

C++
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
try {
std::cout << v.at(5) << '\n';
} catch (const std::out_of_range&) {
std::cout << "index 5 is out of range\n";
}
std::cout << "program continues\n";
return 0;
}
Output
index 5 is out of range
program continues

Throwing your own

C++
#include <iostream>
#include <stdexcept>
int parse_age(int value) {
if (value < 0 || value > 150) throw std::invalid_argument("age out of range");
return value;
}
int main() {
for (int v : {25, -3}) {
try {
int age = parse_age(v); // may throw: compute before printing anything
std::cout << "age " << age << '\n';
} catch (const std::invalid_argument& e) {
std::cout << "error: " << e.what() << '\n';
}
}
return 0;
}
Output
age 25
error: age out of range

More examples

Custom exceptions and stack unwinding

C++
#include <iostream>
#include <stdexcept>
#include <string>
class InsufficientFunds : public std::runtime_error {
public:
InsufficientFunds(double need, double have)
: std::runtime_error("insufficient funds"), shortfall(need - have) {}
double shortfall;
};
struct Audit {
explicit Audit(std::string op) : op_(std::move(op)) { std::cout << "begin " << op_ << '\n'; }
~Audit() { std::cout << "end " << op_ << '\n'; }
std::string op_;
};
void withdraw(double& balance, double amount) {
Audit a("withdraw");
if (amount > balance) throw InsufficientFunds(amount, balance);
balance -= amount;
}
int main() {
double balance = 500;
try {
withdraw(balance, 200);
withdraw(balance, 450);
std::cout << "not reached\n";
} catch (const InsufficientFunds& e) {
std::cout << e.what() << ", short by " << e.shortfall << '\n';
} catch (const std::exception& e) {
std::cout << "other: " << e.what() << '\n';
}
std::cout << "balance " << balance << '\n';
return 0;
}
Output
begin withdraw
end withdraw
begin withdraw
end withdraw
insufficient funds, short by 150
balance 300

Step-by-step explanation

  • InsufficientFunds derives from std::runtime_error and carries extra data.
  • The first withdrawal succeeds; the second throws.
  • Before the handler runs, Audit's destructor prints "end withdraw" — stack unwinding.
  • The specific handler is listed before the general std::exception one.

Expected output

Running “Custom exceptions and stack unwinding” prints exactly:

TextOutput
begin withdraw
end withdraw
begin withdraw
end withdraw
insufficient funds, short by 150
balance 300

Practical applications

  • Web frameworks convert exceptions into HTTP 500 responses.
  • Parsers throw on malformed input.
  • Database libraries throw on connection failures.

Best practices

  • Throw by value, catch by const reference.
  • Derive custom exceptions from std::exception classes.
  • Use RAII so cleanup happens during unwinding.

Common mistakes

Catching by value

Avoid

catch (std::exception e) { }

Prefer

catch (const std::exception& e) { }

By value slices derived exceptions and copies them.

Base handler before derived

Avoid

catch (const std::exception&) {}
catch (const std::out_of_range&) {} // never reached

Prefer

catch (const std::out_of_range&) {}
catch (const std::exception&) {}

Handlers are tried in order; the base handler catches everything first.

Important notes

  • An exception that escapes main (or a noexcept function) calls std::terminate.
  • Some environments (games, embedded) disable exceptions and use error codes or std::optional/std::expected (C++23) instead.

Key takeaways

  • throw signals, try/catch handles, by const reference.
  • Unwinding runs destructors of local objects.
  • Order handlers from most to least specific.

Try it yourself

  1. 1
    Write int to_int(const std::string&) that wraps std::stoi and rethrows a custom ParseError with the bad text.
  2. 2
    Show that a std::vector member is freed when a constructor throws.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerHow should exceptions be caught?
  • BeginnerWhat happens to local objects when an exception propagates out of a function?
Practise this topic