7

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

Alex
  • 175
  • 1
  • 8
  • 1
    Your `what` method has the [wrong signature](https://en.cppreference.com/w/cpp/error/exception/what). – G.M. Feb 22 '21 at 10:07
  • @G.M. So it should be ```virtual const char* RenterLimitException::what() const throw(){ return "No available copies."; }```? – Alex Feb 22 '21 at 10:11
  • In general, you should the `override` keyword, it would have warned you that your implementation does not override the `what()` method in the base class. – Mansoor Feb 22 '21 at 10:11
  • 1
    In modern C++, use `noexcept` specifier instead of the deprecated `throw()` exception specification. – heap underrun Feb 22 '21 at 10:19

2 Answers2

9

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.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
7

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.

john
  • 85,011
  • 4
  • 57
  • 81