Repository navigation
Expand file tree
/
Copy pathexceptions.cpp
More file actions
133 lines (115 loc) · 4.28 KB
/
Copy pathexceptions.cpp
File metadata and controls
133 lines (115 loc) · 4.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// Exception handling: separate error handling from the normal flow of logic.
// throw / try / catch, standard exceptions, a custom exception hierarchy,
// rethrowing, catch-all, and how destructors still run during stack unwinding.
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// A custom hierarchy: catch BankError to handle any banking problem
class BankError : public std::runtime_error {
public:
explicit BankError(const std::string& message) : std::runtime_error(message) {}
};
class InsufficientFunds : public BankError {
double shortBy;
public:
InsufficientFunds(double requested, double available)
: BankError("insufficient funds"), shortBy(requested - available) {}
double shortfall() const { return shortBy; }
};
class InvalidAmount : public BankError {
static std::string describe(double amount) {
std::ostringstream out;
out << "invalid amount " << amount;
return out.str();
}
public:
explicit InvalidAmount(double amount) : BankError(describe(amount)) {}
};
class Account {
double balance;
public:
explicit Account(double opening) : balance(opening) {}
void withdraw(double amount) {
if (amount <= 0) throw InvalidAmount(amount);
if (amount > balance) throw InsufficientFunds(amount, balance);
balance -= amount;
}
double getBalance() const noexcept { return balance; } // noexcept: promises never to throw
};
// RAII: the destructor does the cleanup, so it happens even when an exception escapes
class ScopeGuard {
std::string resource;
public:
explicit ScopeGuard(std::string r) : resource(std::move(r)) { std::cout << " acquire " << resource << '\n'; }
~ScopeGuard() { std::cout << " release " << resource << '\n'; }
};
double safeDivide(double a, double b) {
if (b == 0) throw std::domain_error("division by zero");
return a / b;
}
void processPayment(Account& account, double amount) {
ScopeGuard lock("account lock");
account.withdraw(amount); // if this throws, 'lock' is still released
std::cout << " paid " << amount << ", balance " << account.getBalance() << '\n';
}
void processAndLog(Account& account, double amount) {
try {
processPayment(account, amount);
} catch (const BankError& e) {
std::cout << " [log] " << e.what() << ", passing it up\n";
throw; // rethrow the same exception to the caller
}
}
int main() {
std::cout << "1. Standard library exceptions\n";
std::vector<int> v = {1, 2, 3};
try {
int x = v.at(10); // at() checks bounds, [] does not
std::cout << x;
} catch (const std::out_of_range&) {
std::cout << " out_of_range: index 10 in a vector of size 3\n";
}
try {
int n = std::stoi("abc");
std::cout << n;
} catch (const std::invalid_argument&) {
std::cout << " invalid_argument: \"abc\" is not a number\n";
}
try {
double ok = safeDivide(10, 4);
std::cout << " 10 / 4 = " << ok << '\n';
double bad = safeDivide(10, 0);
std::cout << bad;
} catch (const std::domain_error& e) {
std::cout << " domain_error: " << e.what() << '\n';
}
std::cout << "\n2. Custom exceptions (most specific catch first)\n";
Account account(1000);
for (double amount : {300.0, -50.0, 5000.0}) {
try {
account.withdraw(amount);
std::cout << " withdrew " << amount << ", balance " << account.getBalance() << '\n';
} catch (const InsufficientFunds& e) {
std::cout << " " << e.what() << ": short by " << e.shortfall() << '\n';
} catch (const BankError& e) {
std::cout << " bank error: " << e.what() << '\n';
}
}
std::cout << "\n3. Stack unwinding, RAII and rethrow\n";
try {
processAndLog(account, 200);
processAndLog(account, 9999);
std::cout << " (never printed)\n";
} catch (const std::exception& e) {
std::cout << " main caught: " << e.what() << '\n';
}
std::cout << "\n4. catch (...) catches anything\n";
try {
throw 42; // you can throw any type, but prefer classes derived from std::exception
} catch (...) {
std::cout << " caught an exception of unknown type\n";
}
return 0;
}