Igor Lankin Igor Lankin - 3 months ago 17
C# Question

What exception to throw on invalid object state?

I always missed a built-in exception type in c# which would indicate that an object is corrupted. What do you throw in such cases?

Usually I miss it when I realize that a method, that is supposed to work on an object, would fail if the object had a certain state. In such situations I often suspect that this state probably won't be ever reached. But being defensive about it, I'd like to throw an exception just in case it will (e.g. after a future code change).

For method arguments we have

ArgumentException
so we can deny invalid parameters. But for object state? In Java I'd use
IllegalStateException
.

Of course you could argue that the methods, that are actually changing the state, could check for state correctness. And they better should, but then if they don't (say in legacy god classes)?

Edit:

Although
InvalidOperationException
seems to be the best fit, as the accepted answer states (and also this one), please note:

It is subtle, but semantically this has a different meaning than
InvalidOperationException
.
InvalidOperationException
indicates a problem in the "protocol" of the object, which the caller has to obey (e.g. not initialized, closed already, ...). In my case the caller did nothing wrong, it's the object that is broken. I would like to transport exactly that message.

Example:

switch(this._someType) {
case SomeType.A: doSomething(); break;
case SomeType.B: doSomethingElse(); break;
/*...*/
default:
// Unexpected type! Someone introduced a new type and didn't update this.
throw new IllegalStateException("Unknown type "+this._someType);
}

Answer

You should throw InvalidOperationException to indicate that an object has invalid state.

From the MSDN documentation (linked above):

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