A lesson in bad exception practice

Consider this stack trace from an exception thrown by Entity Framework 6.1.3:

Lucky for me, I know which tiny change I made to the code I am working with to induce the exception, and therefore I am pretty confident that I know what caused it. Had I not been so fortunate, this stack trace would have provided almost no help at all with diagnosing what is actually wrong.

Let’s try and decompile the topmost method, GetStoreTypeFromName, which is the one that apparently calls .Single(..) on a sequence without any matches. It looks like this:

This, Ladies And Gentlemen, is in my humble opinion almost unforgivable: It is simply not OK to call .Single(..) on stuff without re-throwing the exception along with information on what we were looking for.

A much improved version of the method would have looked like this:

this way not losing the original exception, still providing information from the callsite telling the caller what’s wrong.

An even better version of the method would provide me with a list of available “store types”, which often provides some great hints about what is wrong:

The next method in the stack trace is called ConfigureColumn, and sadly if you decompile the method, it will be just as cheap with regards to helping us know what was wrong, even though it has all kinds of valuable things to tell us like:

  • which type was it trying to map
  • which property could not be mapped
  • which column in the database was it trying to map to

etc. etc. etc.

Please don’t write code like that.