AdvancedC++ Programming · Lesson 13 of 17 · Updated ·
Exception Handling in C++ — try, catch, throw, Stack Unwinding and Custom Exceptions
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:
- The caller can forget to check the value, and the program carries on with bad data.
- Every function in the chain must check and pass the code upwards, which clutters the code.
- 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
throwcreates 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. Atrycan have severalcatchblocks; the first one that matches runs.
#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;
}
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.
| 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.
#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;
}
open connection
open file
close file
close connection
caught: disk full
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.
#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;
}
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.
#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;
}
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
noexceptafter a function's parameter list promises it will not throw. If an exception escapes it anyway, the program callsstd::terminateand stops. Mark functionsnoexceptwhen they truly cannot fail, such as move constructors and simple getters.- Constructors should throw when they cannot build a valid object (for example, a
Datewith month 13). There is no return value to report an error, so an exception is the right tool. - Destructors must not throw. Destructors are
noexceptby 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 ofthrow;. - Using exceptions for normal control flow, such as ending a loop. They are for unusual errors.
- Owning memory with raw
newin code that can throw: thedeleteis skipped and memory leaks. Use RAII types.
Quick recap
throwraises,trywatches,catchhandles; the first matching catch runs.- Catch by
const &, most specific type first,catch (...)last if at all. - Standard exceptions derive from
std::exceptionand give a message throughwhat(). - Stack unwinding destroys all local objects on the way out, so RAII prevents leaks.
- Derive custom exceptions from
runtime_errorand add your own data. throw;rethrows the same object;noexceptpromises no exceptions; destructors must not throw.