0

I have a class called Person where I use a special variable as a status, if some atributes have wrong values it creates an object with status error. I check the atributes in the class constructor using if-else statement. How can I implement this using throw-catch exceptions? For example I want to check that string values (name and lastName) are not empty and contain only letters

enum Status {
    OK, Error
};

Class Person {
private:
string name;
string lastName;
int age;

public:
Person(string name, string lastName, int age);
Person() {Status = Error;}
~City();

};

Person::Person(string name, string lastName, int age) {
    if (
            name.empty() || //no person with empty name
            lastName.empty() || //no person with empty last name
            age <= 0 || //age is a positive number
            ) {

        status = Error; //wrong parameters, object created with status error
    } else {
        this->name = name; 
        this->lastName = lastName;
        this->age = age;
        status = OK; 
    }
}
primadonna
  • 142
  • 4
  • 12
  • 2
    Which piece are you stuck on, throwing the exception, catching it? This is all standard stuff which will be covered in any decent C++ book, or even [here](https://stackoverflow.com/questions/8480640/how-to-throw-a-c-exception) – john Oct 20 '20 at 14:51
  • Throwing exceptions from inside a constructor is perfectly legal. The complete object will be considered to never have started its life, and its destructor WILL NOT RUN. Destructors for member and base subobjects which have finished their construction will have their destructors invoked automatically during stack unwinding (if the exception is caught anywhere). This is a good reason to always use RAII for resource management... which congratulations you are already doing. – Ben Voigt Oct 20 '20 at 14:54
  • @john: That's not a great duplicate, although I'm sure that a question also exists for "What happens if a constructor exits by throwing an exception instead of returning?" – Ben Voigt Oct 20 '20 at 14:55

0 Answers0