Is there a built in .NET exception that indicates an illegal object state?

C#.NetException

C# Problem Overview


What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time? I don't really see any built-in exception that makes sense. This seems like something that should be in the framework - am I not poking in the right spot?

C# Solutions


Solution 1 - C#

InvalidOperationException maybe?

> The exception that is thrown when a method call is invalid for the object's current state.

Solution 2 - C#

In general you should program your object in such a way that it cannot reach an invalid state. If you find out that your object is in an invalid state then you should throw a SystemException or an exception directly derived from SystemException. This is the answer to the question in the title.

However, the exceptional circumstance that you are referring to in the question text is a user of your object pushing it into an illegal state. In that case InvalidOperationException is the right exception to throw, as indicated in this earlier answer. This will avoid your object getting into an illegal state.

Needless to say you need to document how your object should be used. If your object has a long life expectancy or if it is used/shared between different objects then it is nice for a user to be able to request the current state, and to implement ToString to retrieve the current state as text, for instance in a debugging environment / log.

Solution 3 - C#

If at all I'd say System.InvalidProgramException get nearest to what you want. What's wrong with throwing a custom exception?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris Marasti-GeorgView Question on Stackoverflow
Solution 1 - C#Michael StumView Answer on Stackoverflow
Solution 2 - C#Maarten BodewesView Answer on Stackoverflow
Solution 3 - C#Markus NigburView Answer on Stackoverflow