Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ overriding exception::what()

Tags:

c++

exception

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

like image 787
Alex Avatar asked Feb 22 '21 10:02

Alex


2 Answers

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.
like image 156
paxdiablo Avatar answered Sep 28 '22 02:09

paxdiablo


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.

like image 27
john Avatar answered Sep 28 '22 02:09

john