I am designing a Framework library which can be used to store a hierarchically linked set of objects. I need to decide on what exceptions can be thrown by the following methods:
class StoreSession {
StoreLeaf(leaf, parent)
}
When users call StoreLeaf() passing the params and if the leaf is not hierarchically linked to a parent based on some custom rules that I execute, then I need to throw an exception (something like InvalidParentException)
If the object that I am attempting to store already has an entry in the repository, then I also need to throw an exception (something like ObjectAlreadyPresentException)
I referred the FDG and also here, there are no instances of any exceptions that describe these 2 scenarios.
Is there any .NET exception that describes these erroneous conditions? Or even If I have to create a new Exception type, is there any specific .NET exception that I can derive from?
No, there isn’t any specific .NET
Exceptionthat describes these conditions; if there were, they would probably be specific to a data structure that fits your needs and you would be using that instead of writing your own.That said, when the framework first came out, the initial recommendation was to derive from
ApplicationException, however, it was quickly revealed that lead to quite a bit of bloat and was ineffective, so the current practice is to derive custom exceptions directly fromException.However, in your specific case, unless there is an action item you are planning on taking in the face of these exceptions, you should probably just use
InvalidOperationException.If you are going to perform an action on these exceptions, then you might want to consider whether or not you should use exceptions at all; it’s generally bad practice to base business logic off exceptions; you should use return codes/values where possible.