-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathguard-encounter-exception.cc
48 lines (38 loc) · 1.09 KB
/
guard-encounter-exception.cc
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
#include <iostream>
template<typename T>
class ScopeGuard{
public:
ScopeGuard(std::function<T> f) : f_(std::move(f)) {}
~ScopeGuard() {
if (f_){
f_();
}
}
private:
std::function<T> f_;
};
auto handle(const std::string& s) {
std::cout << "start handle: " << s << std::endl;
ScopeGuard<void()> local_guard([&](){
std::cout << "finished handle: " << s << " (by scope guard)." << std::endl;
});
//NOTE: assume there's heavy handling here, e.g. many functions call, complex calculation that costs much time, etc.
auto ul = std::stoul(s); // will throw exception if not convertible
std::cout << "finished handle: " << s << std::endl;
return ul;
}
int main(){
while (true){
std::cout << "waiting for input: ";
std::string s;
std::cin >> s;
try{
auto v = handle(s);
std::cout << "result: " << v << std::endl;
}catch (std::exception& e){
std::cout << e.what() << std::endl;
}
std::cout << std::endl;
}
return 0;
}