C++ Exceptions
Things go wrong: a file is missing, a user enters a negative age, a network connection drops. Exceptions are C++'s mechanism for reporting such errors. The code that detects a problem throws an exception; code further up the call chain that knows how to handle it catches it.
try, throw and catch
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw runtime_error("division by zero");
}
return a / b;
}
int main() {
try {
cout << divide(10, 4) << "\n";
cout << divide(1, 0) << "\n"; // throws
cout << "never printed\n";
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << "\n";
}
cout << "Program continues\n";
}2.5
Error: division by zero
Program continues
When throw executes, the current function stops immediately. The exception travels up the call stack until a matching catch is found; the remaining statements in the try block are skipped. If no handler exists anywhere, the program terminates.
Standard exception types
The <stdexcept> header defines a family of exception classes, all derived from std::exception. Each has a what() method returning the message:
| Exception | Typical meaning |
|---|---|
std::invalid_argument |
an argument has an unacceptable value |
std::out_of_range |
an index or key is outside the valid range |
std::runtime_error |
an error only detectable at runtime |
std::logic_error |
a bug in the program's logic |
std::bad_alloc |
new could not allocate memory |
The standard library throws these itself — for example vector::at() throws out_of_range and stoi throws invalid_argument:
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
try {
cout << v.at(10) << "\n";
} catch (const out_of_range& e) {
cout << "out_of_range caught\n";
}
try {
int n = stoi("forty-two");
cout << n << "\n";
} catch (const invalid_argument& e) {
cout << "invalid_argument caught\n";
}
}out_of_range caught
invalid_argument caught
Multiple catch blocks
A try can have several handlers. They are tested in order, so put the most specific types first. catch (...) catches anything:
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
void process(int code) {
if (code == 1) throw invalid_argument("bad input");
if (code == 2) throw out_of_range("index too big");
if (code == 3) throw runtime_error("disk full");
if (code == 4) throw 42; // any type can be thrown
cout << "code " << code << " processed\n";
}
int main() {
for (int code = 0; code <= 4; code++) {
try {
process(code);
} catch (const invalid_argument& e) {
cout << "Invalid argument: " << e.what() << "\n";
} catch (const logic_error& e) { // out_of_range is a logic_error
cout << "Logic error: " << e.what() << "\n";
} catch (const exception& e) {
cout << "Other std::exception: " << e.what() << "\n";
} catch (...) {
cout << "Unknown exception\n";
}
}
}code 0 processed
Invalid argument: bad input
Logic error: index too big
Other std::exception: disk full
Unknown exception
Tip: Throw by value, catch by
constreference (catch (const exception& e)). Catching by value slices derived exceptions and makes an unnecessary copy.
Custom exception classes
Derive from a standard exception to carry extra information about the error:
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
class InsufficientFunds : public runtime_error {
public:
InsufficientFunds(double needed, double available)
: runtime_error("insufficient funds"), shortBy(needed - available) {}
double shortBy;
};
class Account {
public:
explicit Account(double b) : balance(b) {}
void withdraw(double amount) {
if (amount > balance) throw InsufficientFunds(amount, balance);
balance -= amount;
}
double balance;
};
int main() {
Account acc(100);
try {
acc.withdraw(30);
acc.withdraw(120);
} catch (const InsufficientFunds& e) {
cout << e.what() << ": short by " << e.shortBy << "\n";
}
cout << "Balance: " << acc.balance << "\n";
}insufficient funds: short by 50
Balance: 70
Exceptions and cleanup (RAII)
When an exception leaves a scope, the destructors of all local objects in that scope still run — this is called stack unwinding. That is why RAII types such as vector, string, unique_ptr and file streams never leak, even when errors occur.
noexcept
Marking a function noexcept promises it will not throw. The compiler and library can then optimise (for instance, vector moves elements instead of copying them when growing if the move constructor is noexcept). If a noexcept function does throw, the program terminates.
Test yourself
What happens to the remaining statements in a try block after an exception is thrown?
- They run before the catch
- They are skipped
- They run after the catch
- The program restarts them
Which handler catches every exception type?
- catch (exception e)
- catch (...)
- catch (all)
- catch ()
How should you usually catch exceptions?
- By value
- By pointer
- By const reference
- By rvalue reference