Ethan Granucci
Ethan Granucci

Reputation: 43

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

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

Here is what I have tried:

MyClass::MyClass(){ // Default constructor
    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);
}

How can my function be corrected so it throws a range_error when the index is out of bounds?

Upvotes: 1

Views: 1979

Answers (1)

sweenish
sweenish

Reputation: 5202

Your class should know the size of the array at all times. You can know immediately if the value passed is out of range and just throw.

Your try can't work. operator[]() doesn't throw. It functions as a simple memory offset.

Your function should look more like this:

int MyClass::at(size_t position) const
{
  if (position >= this->m_size) throw std::out_of_range("Bad idx passed to at()");

  return ptr[position];
}

Upvotes: 7

Related Questions