title: What exception to throw on invalid object state?
body: <p>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?</p>
  
  <p>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).</p>
  
  <p>For method arguments we have <code>ArgumentException</code> so we can deny invalid parameters. But for object state? In Java I'd use <code>IllegalStateException</code>.</p>
  
  <p>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)?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Although <code>InvalidOperationException</code> seems to be the best fit, as the accepted answer states (and also <a href="https://stackoverflow.com/questions/259800/is-there-a-built-in-net-exception-that-indicates-an-illegal-object-state">this one</a>), please note:</p>
  
  <p>It is subtle, but semantically this has a different meaning than <code>InvalidOperationException</code>. <code>InvalidOperationException</code> 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.</p>
  
  <p>Example:</p>
  
  <pre><code>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); 
  }
  </code></pre>