How should I use exception handling in this class?

Hi

I have a class E, which overloads the [] operator to return the object at that index position. To deal with an index which doesn't exist, I have:

 
  throw std::out_of_range("bad index");


I have another method of E (call it 'calculate()') which goes something like:

1
2
3
4
5
6
  
  if (!exists(index)) { //check whether object at that index exists
      throw std::out_of_range("bad index");
  }

  obj o = (*this)[index];  


There are quite a few other functions like calculate() which used [] operator.

Am I doing this correctly? Should I be throwing only once - either in the [] operator or in calculate()? If so, which?

Thanks
Last edited on
If you want to check all index accesses, it makes sense implementing the range checking at your [] operator.

A good choice would be, providing both methods. E.g. at the container class std::vector , operator[] is implemented unchecked, but the container provides std::vector.at(), which has range checking.
Last edited on
Topic archived. No new replies allowed.