-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexception1.cpp
53 lines (47 loc) · 1.03 KB
/
exception1.cpp
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
#include <cstring>
#include <string>
#include <iostream>
#include <stdexcept>
#include <iomanip>
struct bool_conversion_error : public std::exception {
typedef std::string string;
explicit bool_conversion_error(const char *str) : s(str)
{}
~bool_conversion_error() throw()
{}
const char* what() const throw()
{
string msg(" ** exception: could not convert string '"+s+"' to boolean.");
return msg.c_str();
}
string s;
};
void convert(const char *str, bool &value)
{
if (! strcmp(str, "yes")) {
value = true;
return;
}
if (! strcmp(str, "no")) {
value = false;
return;
}
throw bool_conversion_error(str);
}
int main()
{
const char *str[] = { "yes", "no", "yep"
};
bool value;
try {
for (int i=0; i<3; ++i) {
convert(str[i],value);
std::cout << "str=" << std::setw(3) << std::right << str[i]
<< " value=" << value << std::endl;
}
}
catch(bool_conversion_error& x) {
std::cerr << x.what() << std::endl;
return 0;
}
}