user3920913
user3920913

Reputation: 125

Throwing an std::out_of_range exception C++

I have the following code below:

template <typename X>
const X& ArrayList<X>::at(unsigned int index) const
{
    try {
       return data[index]; //return the value of the index from the array    
    }
    catch (std::out_of_range outofrange) { //if the index is out of range
       std::cout << "OUT OF RANGE" << outofrange.what(); //throw this exception
    }
}

So if i have an array with values

a = [1,2,3]
a.at(5);

should throw an exception "OUT OF RANGE" but it spits out the value 0. I'm not sure what's going on.

Upvotes: 3

Views: 19253

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361442

My guess is that data[index] doesn't throw exception if the index goes out of range because it is not supported by the type of data. What is the type of data? Is it an array like X data[N]?

If so, then do the check yourself:

template <typename X>
const X& ArrayList<X>::at(unsigned int index) const
{
    if ( index >= _size )
        throw std::out_of_range("ArrayList<X>::at() : index is out of range");
    return data[index]; 
}

Note that _size is assumed to be size of the so-called container data.

Hope that helps.

Upvotes: 4

Related Questions