Note: I can’t use anything that is default.
I am trying to make a very simple exception handling routine or at the very least make something that looks the part. I don’t want to do very much, just throw an exception and print an error message.
in .h
class MyException {
protected: string message;
public:
MyException (string mes) {
this->message = mes;
}
MyException (); // is this necessary ? does it do anything ?
string getMessage() const {
return this->message;
}
};
What I’d want is to have a “PersonException” and “ActivityException”. Might use a template but not sure if that would work out.
class PersonException:public MyException {
public:
PersonException (string message):MyException(message) {
}
};
class PersonValidator {
public:
PersonValidator (Person p) throw (PersonException);
};
in .cpp
void PersonValidator::PersonValidator(Person p) throw (PersonException) {
if (p.getPhone < 0) {
throw PersonException ("Person Number is invalid");
}
What here is wrong or cumbersome, how could it be done better ? and where do I actually print the error message ?
1) The default constructor is not necessary, at least the way you have the code now, so you can remove
2) It’s recommended to derive exceptions from
std::exception.3) You can catch your exceptions by catching a
MyException&, and print the message there :4) Avoid
usingdirectives in headers. Your syntax suggests you have ausing namespace std;in the header. That’s wrong, you should favor full name qualification, at least in headers:etc.
5) Favor pass by const reference instead of pass by value, for complex types:
6) Aim for const correctness:
should be:
since it doesn’t change any members.
7) Use initialization lists:
becomes