Last active
May 29, 2017 12:17
-
-
Save DarinM223/2f3821d7f334c3aefc041840c1dbb18b to your computer and use it in GitHub Desktop.
C++ exception-less C-style error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <system_error> | |
struct PersonError { | |
enum { | |
TOO_OLD = 1, | |
NAME_TOO_SHORT = 2, | |
}; | |
}; | |
class PersonCategory : public std::error_category { | |
public: | |
const char *name() const noexcept override { return "Person"; } | |
std::string message(int err_value) const override { | |
switch (err_value) { | |
case PersonError::TOO_OLD: | |
return "Person too old"; | |
case PersonError::NAME_TOO_SHORT: | |
return "Person's name is too short"; | |
default: | |
return "Unknown error value"; | |
} | |
} | |
}; | |
static const PersonCategory PERSON_CATEGORY; | |
class Person { | |
public: | |
Person(std::string name, int age, std::error_code &err) | |
: name_(name), age_(age) { | |
if (age > 100) { | |
err = std::error_code{PersonError::TOO_OLD, PERSON_CATEGORY}; | |
return; | |
} | |
if (name.size() < 2) { | |
err = std::error_code{PersonError::NAME_TOO_SHORT, PERSON_CATEGORY}; | |
return; | |
} | |
} | |
private: | |
std::string name_; | |
int age_; | |
}; | |
void handlePeople(std::error_code &err) { | |
for (int i = 0; i < 101; i++) { | |
Person bob{"Bob", i, err}; | |
if (err) return; | |
} | |
} | |
int main() { | |
std::error_code err{}; | |
handlePeople(err); | |
if (err) { | |
std::cout << "Error: " << err.message() << "\n"; | |
return -1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment