Show contents
Chapter 1 of 6 · 20 min
Exceptions
By the end of this chapter, you'll be able to
- Throw an exception with throw and catch it with try and catch
- Choose a suitable standard exception and define your own
- Order catch blocks from the most specific to the most general
- Explain how destructors guarantee resources are released during an exception
Throwing and catching
throw throws an exception: the function stops immediately, and the exception travels up to the first catch whose type matches. The standard exceptions are in <stdexcept>:
#include <iostream>
#include <stdexcept>
double divide(double a, double b) {
if (b == 0) {
throw std::invalid_argument("division by zero");
}
return a / b;
}
int main() {
for (double b : {4.0, 0.0}) {
try {
double result = divide(10, b);
std::cout << "10 / " << b << " = " << result << '\n';
} catch (const std::invalid_argument& e) {
std::cout << "Error: " << e.what() << '\n';
}
}
}
10 / 4 = 2.5
Error: division by zero
- You catch by const reference (
const std::invalid_argument&): no copy, and the exception's real type is kept. what()returns the message passed to the constructor.- The most useful standard exceptions:
std::invalid_argument(wrong argument),std::out_of_range(index or value out of bounds),std::runtime_error(error detected at run time, such as an unreadable file). They all inherit fromstd::exception.
Your own exception, and the order of catch blocks
An exception can carry useful information. You define one by inheriting from a standard exception:
#include <iostream>
#include <stdexcept>
#include <string>
class InsufficientFunds : public std::runtime_error {
public:
InsufficientFunds(double balance, double requested)
: std::runtime_error("insufficient balance: " + std::to_string(static_cast<int>(balance)) +
" available, " + std::to_string(static_cast<int>(requested)) + " requested"),
missing_(requested - balance) {}
double missing() const { return missing_; }
private:
double missing_;
};
class Account {
public:
explicit Account(double balance) : balance_(balance) {}
void withdraw(double amount) {
if (amount <= 0) throw std::invalid_argument("invalid amount");
if (amount > balance_) throw InsufficientFunds(balance_, amount);
balance_ -= amount;
}
double balance() const { return balance_; }
private:
double balance_;
};
int main() {
Account a(100);
for (double m : {30.0, -5.0, 200.0}) {
try {
a.withdraw(m);
std::cout << "withdrew " << m << ", " << a.balance() << " left\n";
} catch (const InsufficientFunds& e) {
std::cout << "refused (" << e.what() << "), " << e.missing() << " missing\n";
} catch (const std::exception& e) {
std::cout << "error: " << e.what() << '\n';
}
}
}
withdrew 30, 70 left
error: invalid amount
refused (insufficient balance: 70 available, 200 requested), 130 missing
The catch blocks are tried in order: the first one whose type matches wins. Put the most specific ones first. catch (const std::exception&) last catches all the remaining standard exceptions.
Exceptions and RAII: nothing leaks
When an exception travels up, C++ destroys every local object of the functions it passes through, in reverse order of creation. That's stack unwinding. A file, a connection or a lock managed by an RAII object is therefore always released:
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
struct Trace {
std::string name;
explicit Trace(std::string n) : name(std::move(n)) { std::cout << "+ " << name << '\n'; }
~Trace() { std::cout << "- " << name << '\n'; }
};
void step() {
Trace t("file opened");
throw std::runtime_error("disk full");
}
int main() {
try {
Trace t("connection");
step();
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << '\n';
}
}
+ connection
+ file opened
- file opened
- connection
caught: disk full
The catch receives the exception: every resource has already been released.
Text description of the animation
- Inside the try, a first object is constructed.
- step constructs its own object.
- An exception is thrown: step stops dead.
- Leaving step, its local object is destroyed: its destructor runs.
- Leaving the try block, the connection object is destroyed in turn.
- The catch receives the exception: every resource has already been released.
That's why you never manage a resource with a hand-written new and delete: if an exception happens in between, the delete is never reached. With std::unique_ptr, std::vector or std::ifstream, release is automatic.
Your turn
Worked exercise
Worked exercise: reading an age
Write a function int read_age(const std::string& text) that converts the text with std::stoi, throws std::invalid_argument if the text has extra characters (17yrs), and std::out_of_range if the age isn't between 0 and 150. Test it on 42, abc, 17yrs, 200 and 99999999999, displaying invalid or out of range depending on the exception's type.
Hint 1
std::stoi(text, &read) stores in read the number of characters converted: if it differs from text.size(), characters are left over. stoi itself already throws invalid_argument for abc and out_of_range for a number that's too big.Hint 2
std::out_of_range and std::invalid_argument are two different types: two catch blocks cover every case.Show the solution and common mistakes
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
int read_age(const std::string& text) {
std::size_t read = 0;
int age = std::stoi(text, &read); // throws invalid_argument or out_of_range
if (read != text.size()) throw std::invalid_argument("extra characters: " + text);
if (age < 0 || age > 150) throw std::out_of_range("impossible age: " + text);
return age;
}
int main() {
const std::vector<std::string> tries{"42", "abc", "17yrs", "200", "99999999999"};
for (const auto& s : tries) {
try {
int age = read_age(s);
std::cout << s << " -> " << age << '\n';
} catch (const std::out_of_range&) {
std::cout << s << " -> out of range\n";
} catch (const std::invalid_argument&) {
std::cout << s << " -> invalid\n";
}
}
}
42 -> 42
abc -> invalid
17yrs -> invalid
200 -> out of range
99999999999 -> out of range
A catch with no variable name (catch (const std::out_of_range&)) is allowed when you don't need the exception object.
Common mistakes:
- Writing
std::cout << s << " -> " << read_age(s)on a single line: since C++17,sand" -> "are displayed before the call, and the exception leaves a half-written line. Compute first, display afterwards. - Not checking
read:std::stoi("17yrs")returns 17 with no error, since it stops at the first non-numeric character.
Summary
- 1throw throws an exception, which travels up to the first catch of the right type.
- 2Always catch by const reference, otherwise the exception is sliced.
- 3catch blocks are tried in order: from the most specific to the most general.
- 4A custom exception inherits from a standard exception and can carry data.
- 5During stack unwinding, each local object is destroyed: RAII guarantees resources are released.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.