Inherit exceptions in C ++

I just created an exception hierarchy and want my catch block to display a message of a derived exception. I have 5 exceptions like this:

class ImagetypeException : public TGAException { public: const char* what() const throw(); }; const char* ImagetypeException::what() const throw() { return "Der Bildtyp ist nicht \"RGB unkomprimiert\"."; } 

They are all derived from TGAException, which is derived from std :: exception.

 class TGAException : public std::exception { public: virtual const char* what() const throw(); }; const char* TGAException::what() const throw() { return "Beim Einlesen oder Verarbeiten der TGA-Datei ist ein unerwarteter Fehler aufgetreten!"; } 

So I obviously want to drop them at some point in my code, and thought it might be a good idea to minimize the number of locks I need.

 catch (TGAException e) { cout << e.what() << endl; } 

If I do this like this, the message to be printed is one from the TGAException, but I want it to display more specific derived messages. So what do I need to do to get this to work the way I want?

+6
source share
1 answer

When you catch like this:

 catch (TGAException e) { cout << e.what() << endl; } 

The compiler creates a copy of the original exception and assigns it e. It uses the TGAException copy constructor, so the exception observed inside the catch block is not an ImagetypeException, it is a TGAException. This phenomenon is called a cut of objects.

If you catch it like this:

 catch (const TGAException & e) { cout << e.what() << endl; } 

A copy is not needed, and it will work as you expect.

As a general guide: always check for exceptions by reference and almost always catch them by const.

+9
source

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


All Articles