-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstring_error.cpp
44 lines (41 loc) · 1.15 KB
/
string_error.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
#include <expected>
#include <iostream>
#include <string>
#include <stdexcept>
#include <initializer_list>
enum class Error { None, TooBig, TooSmall, Answer };
using StringOrError = std::expected<std::string,Error>;
auto toString(int n) -> StringOrError {
if (0 > n) {
return std::unexpected{ Error::TooSmall };
}
else if (100 <= n) {
return std::unexpected{ Error::TooBig };
}
else if (42 == n) {
return std::unexpected{ Error::Answer };
}
else {
auto s = std::to_string(n);
return s;
}
}
int main() {
try {
for (auto number : { 1, 99, -1, 100, 42, 99 }) {
auto result = toString(number);
if (result.has_value()) {
std::cout << "Value: " << result.value() << '\n';
}
else {
if (result.error() == Error::Answer) {
throw std::runtime_error("Found the answer");
}
std::cerr << "Error: " << static_cast<int>(result.error()) << '\n';
}
}
}
catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << '\n';
}
}