Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return integer from defined exception in C++

Tags:

c++

c++11

I want to define an exception which returns int. My code is given below. It's showing error.

class BadLengthException : public exception {
    public:
        int x;

    BadLengthException(int n){
        x =n;
    }

    virtual const int what() const throw ()  {
        return x;
    }
};

The error is:

solution.cc:12:22: error: conflicting return type specified for ‘virtual const int BadLengthException::what() const’ virtual const int what() const throw () { ^~~~ In file included from /usr/include/c++/7/exception:38:0, from /usr/include/c++/7/ios:39, from /usr/include/c++/7/ostream:38, from /usr/include/c++/7/iostream:39, from solution.cc:1: /usr/include/c++/7/bits/exception.h:69:5: error: overriding ‘virtual const char* std::exception::what() const’ what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT;

like image 381
CompletelyLost Avatar asked Jan 28 '23 11:01

CompletelyLost


1 Answers

exception::what() returns a const char*, you can't change that. But you can define another method to return the int, eg:

class BadLengthException : public std::length_error {
private:
    int x;
public:
    BadLengthException(int n) : std::length_error("bad length"), x(n) { }
    int getLength() const { return x; }
};

And then call it in your catch statements, eg:

catch (const BadLengthException &e) {
    int length = e.getLength();
    ...
} 
like image 64
Remy Lebeau Avatar answered Feb 06 '23 03:02

Remy Lebeau