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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With