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?
InvalidOperationException maybe?
The exception that is thrown when a method call is invalid for the object's current state.
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.
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