Search code examples
c++throw

what is this syntax mean? operator overloading & throw exception


Saw piece of code in book:

T& operator[](int i) throw(RangeError)
{
    if(i >= 0 && i < sz) return ptr[i];
    throw RangeError();
}

what does the throw(RangeError) mean? Behind a function declaration, I know we can append const, or =0 (for pure virtual), but I have never seen throw(...)


Solution

  • It is an exception-specification. It means that your function tells everyone that it has a limited list of things it can throw. Unfortunately or not, but nothing prevents you actually throwing anything else from the function, but if something unexpected is thrown at runtime, then unexpected() will be called. Exception specifications have been removed in the new C++ standard.

    void f() throw(); //I promise not to throw anything
    void g() throw(A, B, C); // I promise not to throw anything except for A, B, or C
    

    Unlike const-qualifiers, an exception specification is not part of a function's type.