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?