Alex
Alex

Reputation: 201

c++ overriding exception::what()

I have a custom exception which is

class RenterLimitException : public std::exception
{
public:
    const char* what();
};

What is the proper way to override what()? For now, I created this custom in a header file and want to override what() in my cpp file. My function is defined as following:

const char* RenterLimitException::what(){
    return "No available copies.";
}

However, when I use my try/catch block, it doesn't print the message that I gave to my function what(), instead, it prints std::exception My try/catch block is this:

try{
   if (something){
            throw RenterLimitException();}
}
catch(std::exception& myCustomException){
        std::cout << myCustomException.what() << std::endl;
    }

Is it because my try/catch block or it is my what() function? Thanks in advance

Upvotes: 8

Views: 7651

Answers (2)

paxdiablo
paxdiablo

Reputation: 881783

That is not the correct signature for the what method, you should be using const char * what() const noexcept override as per the following complete program:

#include <iostream>

class RenterLimitException : public std::exception {
public:
    const char * what() const noexcept override {
        return "No available copies.";
    }
};

int main() {
    try {
        throw RenterLimitException();
    } catch (const std::exception& myCustomException) {
        std::cout << myCustomException.what() << std::endl;
    }
}

Notice the specific signature used for the override and the catching of a const exception in main (not absolutely necessary but a good idea nonetheless). In particular, note the override specifier, which will cause compilers to actually check that the function you're specifying is a virtual one provided by a base class.

Said program prints, as expected:

No available copies.

Upvotes: 9

john
john

Reputation: 87957

Try this

class RenterLimitException : public std::exception
{
public:
    const char* what() const noexcept;
};

const is part of a function signature. To avoid this kind of error in the future you could also get into the habit of using override

class RenterLimitException : public std::exception
{
public:
    const char* what() const noexcept override;
};

override will give you an error if you get the signature of a virtual function wrong.

Upvotes: 7

Related Questions