Igor Lankin Igor Lankin - 1 year ago 176
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

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

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)?


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
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.


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download