Let's assume we're implementing a custom collection which behaves like a vector and we want to make operator[]
throw some exception if collection is empty. std::vector
has undefined behavior in this case but we want to throw exception. If this was C# we would be probably throwing InvalidOperationException
. But which C++ exception would be the most appropriate/intuitive in this case? I feel std::out_of_range
would not be the best choice as collection is empty so there is no 'range' for which indexing would return a valid (any) element.
The NotImplementedException exception indicates that the method or property that you are attempting to invoke has no implementation and therefore provides no functionality. As a result, you should not handle this error in a try/catch block.
A try block must have at least one catch block to have a finally block.
Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.
We have to explicitly throw the exception and hence we will use throw keyword for that. Using throws keyword is as per our need. If we are handling an exception where it is getting thrown then we can avoid throws, else we will use throws and handle it in the caller.
std::vector::at already does this. So you can use at
method instead of operator []
. It throws std::out_of_range
for invalid index.
Please note that you will have to do significant work to achieve the performance of std::vector
. But still if you want to stick to your own container and want to throw from []
then like at
method std::out_of_range
is the best choice among standard exception classes. Otherwise you need to define your own custom exception class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With