Introduction & Syntax
Exception Handling · Study material
Exception handling in C++ separates the code that detects an error from the code that knows how to deal with it. A function that cannot do its job throws an exception; control jumps out of every function in between – destroying their local objects on the way – until a matching catch block handles it. Exceptions cannot be ignored like return codes, they work in constructors and operators, and together with RAII they guarantee that files, locks and memory are released on every path. This page covers try/throw/catch, the standard exception classes, custom exceptions, stack unwinding, noexcept, exceptions in constructors and destructors, the exception-safety guarantees interviewers ask about, and when to prefer std::optional or std::expected. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all verified on a real C++ compiler.
On this page
- try, throw and catch
- The standard exception hierarchy, catch order and catch(...)
- Custom exception classes
- Stack unwinding and RAII
- Rethrowing, translating and nesting exceptions
- noexcept, destructors, constructors and exception-safety guarantees
try, throw and catch
throw expression; creates an exception object and starts looking for a handler. Code inside a try block is protected; the catch blocks after it are tried in order, and the first whose type matches handles the exception. Execution then continues after the last catch block – never back at the throw.
#include <iostream>
#include <stdexcept>
#include <string>
double divide(double a, double b) {
if (b == 0) throw std::invalid_argument("division by zero"); // throw: stop here and report
return a / b;
}
int main() {
try {
std::cout << divide(10, 4) << '\n';
std::cout << divide(1, 0) << '\n'; // throws: the rest of the try block is skipped
std::cout << "not printed\n";
} catch (const std::invalid_argument& e) { // catch by const reference
std::cout << "error: " << e.what() << '\n';
}
std::cout << "program continues\n";
return 0;
}
2.5 error: division by zero program continues
The standard exception hierarchy
| Class (header) | Meaning | Thrown by, for example |
|---|---|---|
std::exception (<exception>) | base of all standard exceptions; virtual what() | – |
std::logic_error (<stdexcept>) | a bug: a precondition was violated | – |
invalid_argument, domain_error, length_error, out_of_range | specific logic errors | std::stoi, vector::at, string::substr |
std::runtime_error (<stdexcept>) | a problem only detectable at run time | – |
range_error, overflow_error, underflow_error, system_error | specific run-time errors | std::thread, filesystem |
std::bad_alloc (<new>) | memory allocation failed | new, containers |
std::bad_cast, bad_optional_access, bad_variant_access, bad_any_cast | wrong type access | dynamic_cast to reference, optional::value |
Always catch by const reference: it avoids copying and slicing, so what() of a derived class still works. Order catch blocks from most specific to most general, and put catch (...) last.
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
void risky(int kind) {
switch (kind) {
case 1: throw std::out_of_range("index 9 of 3");
case 2: throw std::runtime_error("disk full");
case 3: throw std::string("a string, not an exception class");
case 4: throw 42;
}
}
int main() {
for (int k = 1; k <= 4; ++k) {
try {
risky(k);
} catch (const std::out_of_range& e) { // most specific first
std::cout << "out_of_range: " << e.what() << '\n';
} catch (const std::exception& e) { // any standard exception
std::cout << "exception: " << e.what() << '\n';
} catch (const std::string& s) {
std::cout << "string: " << s << '\n';
} catch (...) { // anything else
std::cout << "unknown exception\n";
}
}
return 0;
}
out_of_range: index 9 of 3 exception: disk full string: a string, not an exception class unknown exception
Custom exception classes
Derive your exceptions from std::runtime_error or std::logic_error (or std::exception). Callers can then catch them specifically, or generically as std::exception, and they can carry extra data about the failure.
#include <iostream>
#include <stdexcept>
#include <string>
// Derive from a standard exception: callers can catch it specifically or as std::exception
class InsufficientFunds : public std::runtime_error {
double needed_;
public:
InsufficientFunds(double balance, double amount)
: std::runtime_error("insufficient funds: balance " + std::to_string(static_cast<int>(balance)) +
", requested " + std::to_string(static_cast<int>(amount))),
needed_(amount - balance) {}
double needed() const noexcept { return needed_; }
};
class Account {
double balance_ = 0;
public:
void deposit(double x) {
if (x <= 0) throw std::invalid_argument("deposit must be positive");
balance_ += x;
}
void withdraw(double x) {
if (x > balance_) throw InsufficientFunds(balance_, x);
balance_ -= x;
}
double balance() const { return balance_; }
};
int main() {
Account a;
a.deposit(500);
try {
a.withdraw(200);
a.withdraw(450);
} catch (const InsufficientFunds& e) {
std::cout << e.what() << " (short by " << e.needed() << ")\n";
}
try { a.deposit(-5); } catch (const std::exception& e) { std::cout << e.what() << '\n'; }
std::cout << "balance " << a.balance() << '\n';
return 0;
}
insufficient funds: balance 300, requested 450 (short by 150) deposit must be positive balance 300
Stack unwinding and RAII
When an exception leaves a function, every fully constructed local object in that function is destroyed, in reverse order – this is stack unwinding. That is why RAII (resources owned by objects with destructors) makes C++ code exception-safe automatically: smart pointers, lock guards and file streams release their resources whatever happens.
#include <iostream>
#include <stdexcept>
#include <string>
struct Guard {
std::string name;
explicit Guard(std::string n) : name(std::move(n)) { std::cout << "acquire " << name << '\n'; }
~Guard() { std::cout << "release " << name << '\n'; }
};
void level3() { Guard g("file"); throw std::runtime_error("parse failed"); }
void level2() { Guard g("lock"); level3(); std::cout << "never\n"; }
void level1() { Guard g("connection"); level2(); }
int main() {
try {
level1();
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << '\n'; // every Guard was released on the way here
}
return 0;
}
acquire connection acquire lock acquire file release file release lock release connection caught: parse failed
Rethrowing, translating and nesting
Inside a catch block, throw; rethrows the current exception unchanged (with its real dynamic type). throw e; would throw a copy of the caught type – sliced if caught as a base class. To turn a low-level error into a higher-level one without losing the cause, use std::throw_with_nested and later std::rethrow_if_nested.
#include <iostream>
#include <stdexcept>
#include <string>
struct DbError : std::runtime_error { using std::runtime_error::runtime_error; };
void query() { throw DbError("connection reset"); }
void load_user() {
try {
query();
} catch (const std::exception& e) {
std::cout << "log: " << e.what() << '\n';
throw; // rethrow the ORIGINAL exception (keeps its real type)
}
}
void load_profile() {
try {
load_user();
} catch (const DbError& e) {
// translate a low-level error into a higher-level one, keeping the cause
std::throw_with_nested(std::runtime_error("could not load profile"));
}
}
void print_chain(const std::exception& e, int depth = 0) {
std::cout << std::string(depth * 2, ' ') << e.what() << '\n';
try { std::rethrow_if_nested(e); }
catch (const std::exception& inner) { print_chain(inner, depth + 1); }
}
int main() {
try { load_profile(); }
catch (const std::exception& e) { print_chain(e); }
return 0;
}
log: connection reset could not load profile connection reset
noexcept and destructors
noexcept promises that a function will not throw; if it does, std::terminate ends the program. The noexcept(expr) operator asks at compile time whether an expression can throw. Destructors are noexcept by default and must not let exceptions escape – throwing during stack unwinding would terminate the program. Move constructors should be noexcept so containers can use them.
#include <iostream>
#include <stdexcept>
#include <type_traits>
#include <vector>
int safe_add(int a, int b) noexcept { return a + b; } // promises never to throw
int may_throw(int a) { if (a < 0) throw std::domain_error("negative"); return a; }
struct Widget {
~Widget() { std::cout << "~Widget (destructors are noexcept by default)\n"; }
};
int main() {
std::cout << noexcept(safe_add(1, 2)) << noexcept(may_throw(1)) << ' '
<< std::is_nothrow_destructible_v<Widget> << ' '
<< std::is_nothrow_move_constructible_v<std::vector<int>> << '\n';
try {
Widget w;
may_throw(-1);
} catch (const std::domain_error& e) {
std::cout << "caught " << e.what() << '\n';
}
// If a noexcept function DID throw, std::terminate would end the program immediately.
return 0;
}
10 1 1 ~Widget (destructors are noexcept by default) caught negative
Exceptions in constructors
A constructor that cannot create a valid object should throw – there is no return value to check. If it throws, the object never existed: its destructor does not run, but every member and base that was already constructed is destroyed. So keep resources in members that manage themselves (like unique_ptr), never in raw pointers allocated in the constructor body.
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
struct Part {
std::string name;
explicit Part(std::string n) : name(std::move(n)) { std::cout << "+" << name << ' '; }
~Part() { std::cout << "-" << name << ' '; }
};
class Machine {
Part engine_;
std::unique_ptr<Part> wheels_;
Part radio_;
public:
explicit Machine(bool faulty)
: engine_("engine"), wheels_(std::make_unique<Part>("wheels")), radio_("radio") {
if (faulty) throw std::runtime_error("self-test failed");
std::cout << "[Machine ready] ";
}
~Machine() { std::cout << "[~Machine] "; }
};
int main() {
try {
Machine m(true);
} catch (const std::exception& e) {
std::cout << "| " << e.what() << '\n'; // ~Machine never ran, but every member was destroyed
}
return 0;
}
+engine +wheels +radio -radio -wheels -engine | self-test failed
Exception-safety guarantees
| Guarantee | Promise if an exception is thrown | Example |
|---|---|---|
| No-throw | never throws | destructors, swap, move operations |
| Strong | the state is unchanged ("commit or roll back") | vector::push_back, copy-and-swap |
| Basic | no leaks, invariants hold, but the state may have changed | most operations |
| None | anything may happen | avoid |
Exceptions or error values?
Use exceptions for errors that are rare and that the immediate caller usually cannot fix: a missing config file, a broken connection, a failed allocation. For expected, everyday outcomes – "user not found", "invalid input from a form" – return std::optional or std::expected (see Modern C++ Features). Never use exceptions for normal control flow such as ending a loop.
Common mistakes
- Catching by value – copies and slices derived exceptions.
- Catching the base class first – the specific handlers after it are unreachable.
- throw e; instead of throw; when rethrowing – loses the dynamic type.
- Throwing from a destructor – std::terminate.
- Raw new in a constructor before something that can throw – leak.
- Throwing pointers (
throw new MyError) – who deletes it? Throw by value. - Swallowing exceptions with an empty catch (...) – hides real bugs.
Key points to remember
- throw by value, catch by const reference.
- Order catch blocks from specific to general; catch (...) last.
- Derive custom exceptions from std::runtime_error / std::logic_error.
- Stack unwinding destroys locals – RAII makes cleanup automatic.
- throw; rethrows the original exception.
- Destructors and moves should be noexcept; a throwing noexcept function terminates.
- Constructors signal failure by throwing; the destructor then does not run.
Frequently asked questions
What happens if an exception is never caught?
std::terminate is called, which by default aborts the program (whether the stack is unwound first is implementation-defined).
Are exceptions slow?
With modern "zero-cost" implementations, code that does not throw runs at full speed; throwing and catching is relatively expensive, which is why exceptions are for exceptional situations.
Can I throw any type?
Yes – ints, strings, anything copyable or movable – but throwing classes derived from std::exception is the convention, so callers can catch everything with one handler and call what().
Where can I learn more?
Read C++ Exception Handling, then practise with the exercises below.