-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexceptions_4.cc
More file actions
101 lines (93 loc) · 2.11 KB
/
exceptions_4.cc
File metadata and controls
101 lines (93 loc) · 2.11 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
#include <iostream>
#include <stdlib.h>
#include <stdexcept>
#include <time.h>
using namespace std;
class CurveBall
{
public:
CurveBall(std::string message = "CurveBall")
: message(message)
{}
std::string
what() const
{
return message;
}
private:
std::string message;
};
class NegativeNumber : public std::domain_error
{
public:
NegativeNumber (std::string faultyInput)
: std::domain_error ("User entered a Negative Number: " + faultyInput)
{}
};
class NotANumber : public std::domain_error
{
public:
NotANumber (std::string faultyInput)
: std::domain_error("User entered Non Numeric Value: " + faultyInput)
{}
};
class OddNumber : public std::domain_error
{
public:
OddNumber (std::string faultyInput)
: std::domain_error("User entered an Odd Number: " + faultyInput)
{}
};
int
readEvenNumber ()
{
int randomNum = (rand() % 100);
if (randomNum < 25) {
throw CurveBall();
}
int num;
std::cin >> num;
if (! std::cin.fail()) {
if (num < 0) {
throw NegativeNumber {std::to_string(num)};
} else if ((num % 2) != 0) {
throw OddNumber {std::to_string(num)};
}
return num;
}
std::cin.clear();
std::string line;
std::getline(std::cin, line);
throw NotANumber {line};
}
void
askEvenNumber ()
{
cout << "Please enter an even number" << endl;
try {
auto num = readEvenNumber();
cout << "Thanks for entering " << num << endl;
} catch (const NotANumber &ex) {
cout << ex.what() << endl;
} catch (const OddNumber &ex) {
cout << ex.what() << endl;
askEvenNumber();
} catch (const NegativeNumber &ex) {
cout << ex.what() << endl;
askEvenNumber();
} catch (const std::exception &ex) {
cout << "std::exception caught " << ex.what() << endl;
throw;
}
}
int
main (int argc, char *argv[])
{
srand(time(NULL));
try {
askEvenNumber();
} catch (const CurveBall &ex) {
cout << ex.what() << " Throw it out of the park!" << endl;
}
return 0;
}