Sunday, December 21, 2008

MemberAccessException

Exceptions are meant for those exceptional conditions that never should happened during your programs lifetime, but that you cannot guarantee won't happen. As you might expect from this statement, I'm not a big fan of sprinkling the code with unnecessary exception throws. I find it more useful to test those exceptional cases using unit and integration tests.

Anyway; while studying the source code from the excellent CodeProject article "NHibernate Best Practices with ASP.NET" by Billy McCafferty, I came across this quite interesting use of MemberAccessException;
public IOrderDao OrderDao
{
  get
  {
    if (orderDao == null) {
      throw new MemberAccessException("OrderDao has not yet been initialized");
    }
    return orderDao;
  }
  set { orderDao = value; }
}
If it were me coding this, I’d probably just throw the far more general ApplicationException or something (if I'd throw it all, mind my words in the intro to this post). But I definitely see that the MemberAccessException would be a lot better fit for this exceptional case.

1 comment:

Anonymous said...

I'd have a hard time with using MemberAccessException for this because MemberAccessException is specific to reflection. InvalidOperationException has the right semantics: the call is invalid for the object's current state. Derive a subclass such as ObjectNotInitializedException to mirror ObjectDisposedException (which also derives from InvalidOperationException).