Exception Handling syntax problems in a simple way

Note. I cannot use anything by default.

I am trying to make a very simple exception handling procedure or at least do something that looks like that. 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; } }; 

I would like to have a "PersonException" and an "ActivityException". May use a template, but not sure if this will work.

 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 is wrong or cumbersome here, how can this be done better? and where do I really print the error message?

+4
source share
2 answers

1) The default constructor is not needed , at least you have the code now, so you can delete

  MyException (); 

2) It is recommended to throw exceptions from std::exception .

3) You can catch your exceptions by catching MyException& and typing a message there:

 try { PersonValidator validator(Person()); } catch(const MyException& ex) { std::cout << ex.getMessage(); } 

4) Avoid using directives in headers. . Your syntax tells you there is using namespace std; . This is wrong, you must approve the full name, at least in the headers:

 protected: std::string message; MyException (std::string mes) 

and etc.

5) Use pass by const reference instead of passing by value for complex types:

 MyException (const std::string& mes) PersonValidator (const Person& p) 

6) The goal for constant correctness :

 std::string getMessage() 

it should be:

 std::string getMessage() const 

since he does not change any members.

7) Use initialization lists :

  MyException (string mes) { this->message = mes; } 

becomes

  MyException (string mes) : message(mes) { } 
+10
source

you can also use the default constructor to initialize to some predefined value.

 MyException () : message ("throwing an exception") {}; 
0
source

Source: https://habr.com/ru/post/1412574/


All Articles