vendredi 27 août 2021

overriding the what function in std::exception in c++

I'm trying to override the what function in order to print customized error messages of my own.

all messages have the same beginning and therefore I thought that it would be best if I could do the following :

class Exception : public std::exception
{
    public:
    virtual const char* what() const throw() noexcept
    {
        return ("A game related error has occurred: " +  "class name");
        //note : "class name" above is the error message I want to print 
        //depending on the situation, which can vary a lot(we have 8 different messages)
    }
};


//examples of "class name" /otherwise known by us as error messages:

class IllegalArgument : public Exception {};

class IllegalCell  : public Exception {};

my problem is the following :

I couldn't quite figure out how I can print a varying message depending on which error I receive without making a special what function in each error class - meaning I had to add a what function to IllegalArgument,IllegalCell and every other error class, which is bad in my eyes because it's too many functions to uphold and keep updating overtime. is there anyway I can avoid that, and just be able to print a varying message in the main class - Exception?

Aucun commentaire:

Enregistrer un commentaire