Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug "The type initializer for 'my class' threw an exception"

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 ?

like image 768
JF Beaulieu Avatar asked Sep 06 '12 17:09

JF Beaulieu


3 Answers

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
}
like image 90
spender Avatar answered Nov 09 '22 19:11

spender


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>
like image 5
kombsh Avatar answered Nov 09 '22 20:11

kombsh


This exception is thrown when the static constructor of 'my class' crashes. Please put your breakpoint there.

like image 1
petro.sidlovskyy Avatar answered Nov 09 '22 21:11

petro.sidlovskyy