user83676
user83676

Reputation: 379

Error when trying to implement exceptions in C++

error: declaration of 'virtual const char* numberOutOfBounds::what() const' has a different exception specifier

I have been searching around for a solution and I cannot find out what I'm doing wrong.

exceptions from my header file:

class FileException:public exception {
public:
    virtual const char* what() const throw();
};

class numberOutOfBounds:public exception {
public:
    virtual const char* what() const throw();
};

And the exceptions in my cpp file:

const char* FileException::what() const {
    return "Cannot open file";
}

const char* numberOutOfBounds::what() const {
    return "illegal number entered";
}

Can someone let me know what I am doing incorrectly here? I have looked around and can't figure out why I am getting the error message that I am getting.

Upvotes: 0

Views: 1064

Answers (2)

vishal
vishal

Reputation: 2391

the correct way to implement an exception:

class myexception: public exception {
virtual const char *what() const throw()
{
 return "Exception occured!!";
}
 }myexc;

int main () {
try
{
    throw myex;
}
catch (exception& e)
{
    cout << e.what() << '\n';
}
return 0;
}

Upvotes: 0

James Adkison
James Adkison

Reputation: 9602

virtual const char* what() const throw();

This function declaration has a throw declaration but it's missing from the definition.

You need:

const char* FileException::what() const throw() {
                                     // ^^^^^^^ - added
    return "Cannot open file";
}

FYI, there is already a std::out_of_range exception class.

Upvotes: 2

Related Questions