Exceptions
Exceptions are a control-flow path for failures that the immediate caller cannot handle. throw starts stack unwinding; destructors of local objects run; the first matching catch handles the object that was thrown.
Detailed Explanation
You open a config file, parse it, and build a cache. Any of those steps can fail. Checking an error code after every call works, and it is what C APIs do. It also means every caller must remember to check. Miss one and the program continues with a half-built cache. Exceptions invert the default: failure jumps to a handler, and every RAII object on the way out cleans up.
throw expr; copies or moves expr into an exception object that lives in a compiler-managed area, then walks up the stack. For each scope, destructors of fully constructed locals run. That walk is stack unwinding. It stops at a catch clause whose type matches the exception (same type, a public base, or catch (...)). After the handler, execution continues after the try block, not after the throw.
You throw by value and catch by reference: catch (const std::exception& e). Catching by value slices derived types. Catching a pointer is a different type than catching the object; do not mix throw new with catch (const std::exception&).
The standard hierarchy starts at std::exception. std::runtime_error and std::logic_error split "something went wrong in the world" from "the program broke its own contract". std::out_of_range, std::invalid_argument, std::system_error sit under those. You can throw any copy-constructible type, including an int. Don't. Throw a type that carries a message and sits in the hierarchy so catch (const std::exception&) still works.
try / catch is for boundaries: a thread's entry function, a request handler, a main that must log and continue. Do not wrap every vector::at in its own try. An exception means "this operation failed as a whole". If the caller can recover locally (retry, use a default), a return type (std::optional, std::expected in C++23, or a bool plus out-parameter) is often clearer.
Exceptions and RAII are a pair. Without destructors that release resources, unwinding leaks. With them, a function that throws after opening three files does not need a cleanup label. The rule that makes this safe: never throw from a destructor. If a destructor throws during unwinding, std::terminate is called.
Cost: a throw is slow compared to a branch. The hot path with no exception is designed to be cheap (modern ABIs use a side table, not a register tax on every call). That is why exceptions are for rare failures, not for "this loop found the item". std::vector::operator[] does not throw; at does. Pick the one that matches the failure policy.
If no handler exists, std::terminate runs. The default terminates the process. A function marked noexcept that throws also calls terminate. There is no Java-style finally; the destructor is the finally.
Code Examples
#include <iostream>
#include <stdexcept>
#include <string>
int parsePort(const std::string& text) {
if (text.empty()) throw std::invalid_argument("empty port");
int port = std::stoi(text); // throws std::invalid_argument / out_of_range
if (port < 1 || port > 65535) throw std::out_of_range("port");
return port;
}
int main() {
try {
std::cout << parsePort("8080") << '\n'; // prints: 8080
std::cout << parsePort("0") << '\n';
} catch (const std::exception& e) {
std::cout << "failed: " << e.what() << '\n'; // prints: failed: port
}
}#include <fstream>
#include <stdexcept>
#include <string>
std::string slurp(const std::string& path) {
std::ifstream in(path);
if (!in) throw std::runtime_error("cannot open " + path);
std::string body((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
return body; // if later code throws, `in` still closes in its destructor
}Common Gotchas
Catch by reference
`catch (std::exception e)` slices a `std::runtime_error` down to `std::exception` and drops the message type. Write `catch (const std::exception& e)`.
`catch (...)` swallows everything
including things you did not throw, on some platforms. Log and rethrow (`throw;`) unless you are at a true boundary such as a thread root.