vendredi 26 juin 2020

Exceptions Using Inheritance?

I wrote the following code:

class GameException : public mtm::Exception {
};

class IllegalArgument : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalArgument";
    }
};

class IllegalCell : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalCell";
    }
};

How may I use inheritance here to prevent some code duplication? As you can see I'm returning the same sentence but with different ending (Which is the class name). I though about implementing GameException as the following:

class GameException : public mtm::Exception {
     std::string className;
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: "+className;
    }
};

But how may I change the value of className for the rest of my classes? Plus, I'm getting the error:

No viable conversion from returned value of type 'std::__1::basic_string' to function return type 'const char *'

Aucun commentaire:

Enregistrer un commentaire