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); }
Class InvalidStateExceptionThrown by an instance of Peripheral to indicate that an operation as been attempted at an inappropriate time. In other words, the peripheral device is not in an appropriate state for the requested operation.
InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an InvalidOperationException exception is thrown by methods such as: IEnumerator.
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.
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