抛出std :: out_of_range异常C ++

时间:2014-08-11 05:07:24

标签: c++ exception

我在下面有以下代码:

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
    }
}

所以,如果我有一个值为

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

应该抛出一个异常“OUT OF RANGE”,但它会吐出值0.我不确定发生了什么。

1 个答案:

答案 0 :(得分:3)

我的猜测是,如果索引超出范围,data[index]不会抛出异常,因为data的类型不支持它。 data的类型是什么?它是一个像X data[N]的数组吗?

如果是,请自行检查:

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]; 
}

请注意,_size被假定为所谓的容器data的大小。

希望有所帮助。