What exception is thrown when the current state of the object does not allow an operation to be performed on it?

Suppose we implement a custom collection that behaves like a vector, and we want to make operator[] throw an exception if the collection is empty. std::vector has undefined behavior in this case, but we want to make an exception. If it were C #, we would probably InvalidOperationException . But which C ++ exception would be most appropriate / intuitive in this case? I feel that std::out_of_range would not be the best choice since the collection is empty, so there is no range for which indexing will return valid (any).

+5
source share
1 answer

std :: vector :: at already does this. That way you can use the at method instead of operator [] . It rejects std::out_of_range for an invalid index.

Please note that you will need to do significant work to achieve std::vector performance. But still, if you want to stick to your container and want to get out of [] , then the at std::out_of_range method is the best choice among the standard exception classes. Otherwise, you need to define your own custom exception class.

+4
source

Source: https://habr.com/ru/post/1271364/


All Articles