Thursday, August 07, 2008

When to use InvalidOperationException

I was out with friends the other day in a bar and somehow we started talking about when to throw InvalidOperationException from within your application code (exciting I know! :). I thought I'd clear this up as it can be a slightly gray area.

The description on MSDN is as follows: "The exception that is thrown when a method call is invalid for the object's current state".

So it should only ever be thrown if state within the class is not correct for the executing method.

A snip from Framework Design Guidelines book regarding InvalidOperationException is as follows: "Do throw an InvalidOperationException if the object is in an inappropriate state. The System.InvalidOperationException exception should be thrown if a property set or a method call is not appropriate given the objects current state. An example of this is writing to a FileStream that's been opened for reading.".

MSDN goes on comparing the difference between InvalidOperationException and ArgumentException and ArgumentNullException with: "If the method invocation failure is due to invalid arguments, then ArgumentException or one of its derived classes, ArgumentNullException or ArgumentOutOfRangeException, should be thrown instead.".


1 comment:

Chris Nevill said...

I for one am impressed you have friends that know what you're talking about. Most of my friends eyes glaze the moment I say I do software development.