rgamber
rgamber

Reputation: 5849

Exception inheritance

Is it possible to have multiple elements in an exception class in c++, which I can associate with the exception, so that when I throw it, the user can gather more information about the exception than just an error message? I have the below class

#include <list>
using namespace std;

class myex : public out_of_range {
private:
    list<int> *li; 
    const char* str = "";
public:
    //myex(const char* err): out_of_range(err) {}
    myex(li<int> *l,const char* s) : li(l),str(s) {}

    const char* what(){ 
        return str;
    }       
};

When I throw a myex using

throw myexception<int>(0,cont,"Invalid dereferencing: The iterator index is out of range.");, 

I get an error

error: no matching function for call to ‘std::out_of_range::out_of_range()’.
Any help is appreciated.`.

When I uncomment the commented line, and remove the other constructor, then it works fine.

Upvotes: 0

Views: 645

Answers (1)

Nbr44
Nbr44

Reputation: 2062

The constructor of your user-defined exception tries to call the default constructor of the class out_of_range... Except it doesn't exist !

About the commented constructor :

myex(const char* err): out_of_range(err) {}
                     //^^^^^^^^^^^^^^^^^ this calls the constructor of 
                     // out_of_range with the parameter err.

In order to fix your current constructor, you should add an explicit call to out_of_range's constructor (which takes a const string&):

myex(li<int> *l,const char* s) : out_of_range(s), li(l),str(s) {}

Upvotes: 2

Related Questions