0

so I have a problem with this:

class Exception{
    private : string message;
    public : 
    Exception();
    Exception(string str);
    string what();

};
class Something{
public : Something(int m) throw(Exception);
....}

and in the cpp file:

Exception::Exception()
    {
        message="cant divide by 0";
    }
    Exception::Exception(string str)
    {
        message = str;
    }
    Exception:string what()
    {
        return message;
    }

and then i tried to use it inside some constructor

Something::Something(int m) throw(Exception)
    {
        if (m==0) 
        {
            throw Exception();
        }
     };

and in the main

...
catch(Exception obj){
    cout<<obj.what();

}

and it shows "Exception" does not name a type and 'obj' wasnt declared and I wonder why.

polles
  • 13
  • 2

1 Answers1

0

The Exception class may be incomplete.

It doesn't look to me like Exception::what() is defined correctly.

Try...

string Exception::what()
{
    return message;
}

Also, as others have mentioned, in c++ you don't have to define what a function throws like in java. See this question for more details...

Throw keyword in function's signature

Something::Something(int m)
{
    if (m==0) 
    {
        throw Exception();
    }
};

Also typically I'd catch a reference to the thrown exception unless it is a primitive type. This will avoid making a copy of the exception.

Try...

...
catch(const Exception& obj) {
    cout << obj.what();
}
Clayton Mills
  • 86
  • 1
  • 9