mardi 30 mars 2021

Trying to throw a range error if array index is out of bounds (C++)

I am trying to get my program to throw a stdexcept range_error if the array index my function is accessing is out of bounds. The type passed in is of size_t because the memory location in the stack may be signed or unsigned. Here is what I have tried:

MyClass::MyClass(){ // default constr
    size = 10;
    ptr = new int[size];
} 

int MyClass::at(size_t position) const
{
    try
    {
        return ptr[pos];
    }
    catch (const std::range_error&)
    {
        cout << "Range Error" << endl;
    }
    
}

int main() {
    // Test exceptions
    MyClass a;
    throw_(a.at(0), range_error);
}

If anyone can please help correct my function so it throws a range_error when the index is out of bounds, that would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire