I am getting the exception: The type initializer for 'my class' threw an exception.
in my browser after running my web application. Since this seems to be an error message generated from the view (.aspx), there is no way I can see the stack trace or any log for the source of this error.
I have read a bit around the net and one solution to debugging is to throw a TypeInitializationException
and then looking at the inner exception to find out what was wrong. How can I do this when I don't know where to surround code with a try/catch ?
This can be caused by a bad static constructor, or by bad inline initialization of static properties/fields. For instance:
class A
{
static A()
{
//buggy code here
}
static SomeField f = new ThisClassThrowsWhenConstructed(); // <-- or here
}
Finally I found reason for this issue is AppConfig settings of my project. Yes, I have two C# projects, Project1 and Project2.
Project1 is contains the Static class MyDetails
public static MyDetails
{
public static int _LogLevel = Int32.Parse(ConfigurationManager.AppSettings["LogLevel"])
public static GetData()
{
----code----
----code----
}
}
I have following appConfig settings in Project1
<appSettings>
<add key="LogLevel" value="5"/>
</appSettings>
The function MyDetails.GetData() is being called From Project2 which is the project I am debugging now. Since Project2 is the target project, the line ConfigurationManager.AppSettings["LogLevel"] will try to read setting LogLevel from Project2. but LogLevel setting is only available in Project1. so, we need to add appsettings in Project2.
The issue The type initializer for threw an exception has been solved after adding the folowing appsettings in appConfig of Project2,
<appSettings>
<add key="LogLevel" value="5"/>
</appSettings>
This exception is thrown when the static constructor of 'my class' crashes. Please put your breakpoint there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With