Tuesday, June 18, 2013

TypeInitialization Exception was unhandled

"TypeInitialization Exception was unhandled"... This was a runtime exception which kept me worried for several hours... Couldn't really understand the actually reason for the RTE which started appearing all of a sudden in a project which was working fine for a long time...

Since it was a very high level exception, nailing down the source of the exception was tricky. To understand the source of the exception, IDE changes had to be made in .NET environment. Go to Debug -> Exception -> check all the "Thrown" exception. This will help in identifying the actually piece of code which throws this unhandled exception.

In my case, I had changed the location of the referenced dlls but the new location was not part of the project. As a result, the dlls were not able to load. Things always get tricky in .Net when you are trying to load a dll from a folder or sub-folder which isn't within the EXECUTABLE location. This would be an interesting read on the topic. But technically, this is just one reason for getting the "TypeInitialization Exception", but the way to probe the problem and get to the source of the same can be very similar to the one explained earlier.

Since, we are talking about this exception I would also like to highlight another reason for it. It may also occur when your "Configuration Manager" is set to "Any CPU" when it is supposed to be just "x86". I have personally not encountered this problem, but there are various posts on stackoverflow, which highlights this example.