Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

exception

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?

like image 553
Chris Marasti-Georg Avatar asked Nov 03 '08 20:11

Chris Marasti-Georg


2 Answers

InvalidOperationException maybe?

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

like image 150
Michael Stum Avatar answered Oct 13 '22 01:10

Michael Stum


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.

like image 41
Maarten Bodewes Avatar answered Oct 13 '22 00:10

Maarten Bodewes