Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception to throw when current state of the object does not allow attempted operation on it? [closed]

Tags:

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.

like image 285
Bojan Komazec Avatar asked Aug 30 '17 11:08

Bojan Komazec


People also ask

Which exception is thrown when a requested method does not exist?

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.

Which of the following is true about exception handling every try block should have exactly one catch block?

A try block must have at least one catch block to have a finally block.

What exceptions can be thrown?

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.

Which keyword is used to bypass the exception from current method to caller method?

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.


1 Answers

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.

like image 130
taskinoor Avatar answered Sep 20 '22 22:09

taskinoor