Click to See Complete Forum and Search --> : Exceptions in C++


PolteRGeisT
10-03-2002, 08:01 AM
I have this program (I'll provide only the essentials):


class xBoundaryViolation {
public:
xBoundaryViolation() { cerr << "Boundary Violation..." << endl; }
};

class __string
{
public:
__string();
__string(const char *);
__string(const __string &);
~__string();

friend __string operator+(const __string &, const __string &);
__string &operator+=(const __string &);
__string &operator=(const __string &);

unsigned int length()const { return size; }

char operator[](unsigned index)const;
char &operator[](unsigned index);

friend ostream &operator<<(ostream &__cout, __string &rhs);
friend istream &operator>>(istream &__cin, __string &rhs);


private:
__string(unsigned int);
char *str;
unsigned int size;
};

char __string::operator[](unsigned int offset)const
{
if(offset >= size)
throw xBoundaryViolation;

return *(str + offset);
}

char &__string::operator[](unsigned int offset)
{
if(offset >= size)
throw xBoundaryViolation;

return *(str + offset);
}



And I get these errors.

In method `char
__string::operator[] (unsigned int) const':
parse error before `;
confused by earlier errors, bailing out

the ` ; ` being on the line that throws the exception. I am compiling this with g++ version 2.96

bwkaz
10-03-2002, 09:36 AM
I haven't done much with C++'s exception handling, but in Java, you can't throw anything that doesn't descend from the Throwable interface (it'd be a class in C++). Maybe that?

Or maybe you can't throw a class name, you have to throw an object?

throw xBoundaryViolation();instead, perhaps (so you actually create one)? If you need a pointer to an exception object, just throw "new xBoundaryViolation();".

truls
10-03-2002, 09:43 AM
Dagnabbit, you beat me to it (while I was compiling the code :-).

bwkaz is right, you need to use xBoundaryViolation().