C++, lesson 9
Things go wrong: a user types abc where a number belongs, a withdrawal exceeds the balance, a
file is missing. C++ offers two main tools. Exceptions report problems that the current
function can't handle itself, and std::optional represents a result that may legitimately
be absent.
When a function detects a problem it cannot fix, it throws an exception object. Control
jumps out of the function (and out of any callers) until it reaches a matching catch block.
Everything in between is skipped, and local variables along the way are cleaned up properly.
try { }.catch names the type of exception it handles. Catch by to avoid
copying the exception.2 exercises to try what you just read.
e.what() returns the message the exception was created with.std::terminate).<stdexcept> provides a small family of classes, all derived from std::exception:
std::logic_error covers mistakes the caller could have avoided. Its children include
std::invalid_argument and std::out_of_range.std::runtime_error covers problems only discovered while running, such as std::overflow_error.catch blocks are tried in order, and a handler for a base class also catches every class
derived from it. So list specific handlers first and general ones after:
You can also define your own exception type by deriving from one of these:
std::stoi(text) converts a string to an int. It skips leading spaces and then reads as many
digits as it can. It throws std::invalid_argument if there are no digits at all, and
std::out_of_range if the number doesn't fit in an int. It does not complain about extra
characters after the number: std::stoi("12kg") is 12. To insist on a clean number, pass a
std::size_t by address and check how many characters were used:
std::stoll and std::stod do the same for long long and double.
Not finding something is often normal, not exceptional. C++17's std::optional<T> (from
<optional>) holds either a T or nothing:
The optional converts to true when it holds a value, *pos reads that value, and value_or
supplies a fallback.
Use exceptions for errors that should interrupt the normal flow, std::optional for results
that may simply be absent, and keep try blocks around the code that can actually recover.
A sensor log arrives one value per line, but some lines are damaged. Read lines until the input
ends and convert each with std::stoi:
int (leading spaces allowed, nothing after the digits), print
ok <value> and add it to a running sumstd::stoi throws std::out_of_range, print too big: <line>std::invalid_argument, or there are leftover characters) print
bad: <line>Finally print sum: <sum>.
Write two functions that change a balance and throw when the request is invalid:
void deposit(long long& balance, long long amount) throws std::invalid_argument with the
message amount must be positive if amount <= 0.void withdraw(long long& balance, long long amount) throws the same for amount <= 0, and
throws std::runtime_error with the message insufficient funds if amount > balance.The input starts with the opening balance, followed by commands deposit <amount> or
withdraw <amount> until the input ends. For each command call the right function inside a
try block. On success print OK, balance <balance>; when an exception is caught print
Error: <message>. Any other command word prints Error: unknown command <word>.
#include <stdexcept>
double average(int total, int count) {
if (count == 0) {
throw std::invalid_argument("count must not be zero");
}
return static_cast<double>(total) / count;
}
int main() {
try {
std::cout << average(10, 0) << '\n';
std::cout << "never printed\n";
} catch (const std::invalid_argument& e) {
std::cout << "Error: " << e.what() << '\n'; // Error: count must not be zero
}
}try {
process();
} catch (const std::out_of_range& e) {
// just this kind
} catch (const std::exception& e) {
// any other standard exception
}class insufficient_funds : public std::runtime_error {
public:
using std::runtime_error::runtime_error; // reuse the constructors
};std::size_t used{};
int value{std::stoi(text, &used)};
if (used != text.size()) {
// there was something after the number
}#include <optional>
std::optional<int> find_index(const std::vector<int>& v, int target) {
for (std::size_t i = 0; i < v.size(); ++i) {
if (v[i] == target) return static_cast<int>(i);
}
return std::nullopt; // nothing found
}
if (auto pos = find_index(scores, 95)) {
std::cout << "found at " << *pos << '\n';
}
std::cout << find_index(scores, 7).value_or(-1) << '\n';Input:
12
-7
3kg
hello
Output:
ok 12
ok -7
bad: 3kg
bad: hello
sum: 5Input:
100
withdraw 30
withdraw 500
deposit -5
deposit 20
Output:
OK, balance 70
Error: insufficient funds
Error: amount must be positive
OK, balance 90