The STL and professional C++ · Lesson 19 of 21
Exceptions
throw, try and catch, the standard error types, and how RAII fits in.
When a function hits something it can't continue with (bad input, a missing file), it can throw an exception. Execution stops at once and unwinds outward to the nearest matching catch. With no catch at all, the program terminates.
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
double average(const std::vector<int>& v) {
if (v.empty()) throw std::invalid_argument("average of an empty list");
int sum = 0;
for (int x : v) sum += x;
return static_cast<double>(sum) / v.size();
}
int main() {
try {
std::cout << average({80, 90}) << "\n";
std::cout << average({}) << "\n"; // throws
std::cout << "never printed\n";
} catch (const std::invalid_argument& e) {
std::cout << "bad input: " << e.what() << "\n";
}
std::vector<int> v = {1, 2, 3};
try {
std::cout << v.at(10) << "\n";
} catch (const std::out_of_range& e) {
std::cout << "out of range\n";
}
std::cout << "still running\n";
return 0;
}- std::exception
- std::logic_error
- std::invalid_argument
- std::out_of_range
- std::runtime_error
- std::overflow_error
- std::bad_alloc (new failed)
- std::logic_error
The standard types form a tree: catch (const std::exception& e) catches any of them.
What's the output?
#include <iostream>
#include <stdexcept>
struct Guard {
~Guard() { std::cout << "G"; }
};
void risky() {
Guard g;
std::cout << "1";
throw std::runtime_error("x");
std::cout << "2";
}
int main() {
try { risky(); } catch (const std::exception&) { std::cout << "C"; }
std::cout << "\n";
}What will this code print?
Exercise
Write int toPercent(int part, int whole) that throws std::invalid_argument when whole is zero and otherwise returns part * 100 / whole. In main: print toPercent(3, 4), then try toPercent(1, 0), catch the exception and print error.
75 error
#include <iostream>
#include <stdexcept>
int toPercent(int part, int whole) {
return part * 100 / whole;
}
int main() {
std::cout << toPercent(3, 4) << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.