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

烈酒焚心 提交于 2019-12-21 12:16:22

问题


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 ?


回答1:


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
}



回答2:


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>



回答3:


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




回答4:


There is something that when wrong in your static constructor of the class, and instead of throwing that error, the CLR will throw TypeInitializationException.



来源:https://stackoverflow.com/questions/12305648/how-to-debug-the-type-initializer-for-my-class-threw-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!