TypeInitializationException Class
TOC
Collapse the table of content
Expand the table of content

TypeInitializationException Class

 

The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Exception
    System.SystemException
      System.TypeInitializationException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class TypeInitializationException : SystemException

NameDescription
System_CAPS_pubmethodTypeInitializationException(String, Exception)

Initializes a new instance of the TypeInitializationException class with the default error message, the specified type name, and a reference to the inner exception that is the root cause of this exception.

NameDescription
System_CAPS_pubpropertyData

Gets a collection of key/value pairs that provide additional user-defined information about the exception.(Inherited from Exception.)

System_CAPS_pubpropertyHelpLink

Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)

System_CAPS_pubpropertyHResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)

System_CAPS_pubpropertyInnerException

Gets the Exception instance that caused the current exception.(Inherited from Exception.)

System_CAPS_pubpropertyMessage

Gets a message that describes the current exception.(Inherited from Exception.)

System_CAPS_pubpropertySource

Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)

System_CAPS_pubpropertyStackTrace

Gets a string representation of the immediate frames on the call stack.(Inherited from Exception.)

System_CAPS_pubpropertyTargetSite

Gets the method that throws the current exception.(Inherited from Exception.)

System_CAPS_pubpropertyTypeName

Gets the fully qualified name of the type that fails to initialize.

NameDescription
System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.(Inherited from Exception.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Sets the SerializationInfo object with the type name and additional exception information.(Overrides Exception.GetObjectData(SerializationInfo, StreamingContext).)

System_CAPS_pubmethodGetType()

Gets the runtime type of the current instance.(Inherited from Exception.)

System_CAPS_pubmethodToString()

Creates and returns a string representation of the current exception.(Inherited from Exception.)

When a class initializer fails to initialize a type, a TypeInitializationException is created and passed a reference to the exception thrown by the type's class initializer. The InnerException property of TypeInitializationException holds the underlying exception.

Typically, the TypeInitializationException exception reflects a catastrophic condition (the runtime is unable to instantiate a type) that prevents an application from continuing. Most commonly, the TypeInitializationException is thrown in response to some change in the executing environment of the application. Consequently, other than possibly for troubleshooting debug code, the exception should not be handled in a try/catch block. Instead, the cause of the exception should be investigated and eliminated.

TypeInitializationException uses the HRESULT COR_E_TYPEINITIALIZATION, which has the value 0x80131534.

For a list of initial property values for an instance of TypeInitializationException, see the TypeInitializationException constructors.

The following sections describe some of the situations in which a TypeInitializationException exception is thrown.

Static constructors and the TypeInitializationException exception
Regular expression match timeout values
Calendars and cultural data

A static constructor, if one exists, is called automatically by the runtime before creating a new instance of a type. Static constructors can be explicitly defined by a developer. If a static constructor is not explicitly defined, compilers automatically create one to initialize any static (in C#) or Shared (in Visual Basic) members of the type. For more information on static constructors, see Static Constructors (C# Programming Guide).

Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type. The InnerException property indicates why the static constructor was unable to instantiate the type. Some of the more common causes of a TypeInitializationException exception are:

An unhandled exception in a static constructor

If an exception is thrown in a static constructor, that exception is wrapped in a TypeInitializationException exception, and the type cannot be instantiated.

What often makes this exception difficult to troubleshoot is that static constructors are not always explicitly defined in source code. A static constructor exists in a type if:

  • It has been explicitly defined as a member of a type.

  • The type has static (in C#) or Shared (in Visual Basic) variables that are declared and initialized in a single statement. In this case, the language compiler generates a static constructor for the type. You can inspect it by using a utility such as IL Disassembler. For instance, when the C# and VB compilers compile the following example, they generate the IL for a static constructor that is similar to this:

    
    .method private specialname rtspecialname static 
            void  .cctor() cil managed
    {
      // Code size       12 (0xc)
      .maxstack  8
      IL_0000:  ldc.i4.3
      IL_0001:  newobj     instance void TestClass::.ctor(int32)
      IL_0006:  stsfld     class TestClass Example::test
      IL_000b:  ret
    } // end of method Example::.cctor
    
    

The following example shows a TypeInitializationException exception thrown by a compiler-generated static constructor. The Example class includes a static (in C#) or Shared (in Visual Basic) field of type TestClass that is instantiated by passing a value of 3 to its class constructor. That value, however, is illegal; only values of 0 or 1 are permitted. As a result, the TestClass class constructor throws an ArgumentOutOfRangeException. Since this exception is not handled, it is wrapped in a TypeInitializationException exception.

using System;

public class Example
{
   private static TestClass test = new TestClass(3);

   public static void Main()
   {
      Example ex = new Example();
      Console.WriteLine(test.Value);
   }
}

public class TestClass
{
   public readonly int Value;

   public TestClass(int value)
   {
      if (value < 0 || value > 1) throw new ArgumentOutOfRangeException();
      Value = value;
   }
}
// The example displays the following output:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'Example' threw an exception. ---> 
//       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
//       at TestClass..ctor(Int32 value)
//       at Example..cctor()
//       --- End of inner exception stack trace ---
//       at Example.Main()

Note that the exception message displays information about the InnerException property.

A missing assembly or data file

A common cause of a TypeInitializationException exception is that an assembly or data file that was present in an application's development and test environments is missing from its runtime environment. For example, you can compile the following example to an assembly named Missing1a.dll by using the this command-line syntax:

csc /t:library Missing1a.cs
using System;

public class InfoModule
{
   private DateTime firstUse;
   private int ctr = 0;

   public InfoModule(DateTime dat)
   {
      firstUse = dat;
   }

   public int Increment()
   {
      return ++ctr;
   }

   public DateTime GetInitializationTime()
   {
      return firstUse;
   }
}

You can then compile the following example to an executable named Missing1.exe by including a reference to Missing1a.dll:

csc Missing1.cs /r:Missing1a.dll

However, if you rename, move, or delete Missing1a.dll and run the example, it throws a TypeInitializationException exception and displays the output shown in the example. Note that the exception message includes information about the InnerException property. In this case, the inner exception is a FileNotFoundException that is thrown because the runtime cannot find the dependent assembly.

using System;

public class Example
{
   public static void Main()
   {
      Person p = new Person("John", "Doe");
      Console.WriteLine(p);   
   }
}

public class Person
{
   static InfoModule infoModule;

   String fName;
   String mName;
   String lName;

   static Person()
   {
      infoModule = new InfoModule(DateTime.UtcNow);
   }

   public Person(String fName, String lName)
   {
      this.fName = fName;
      this.lName = lName;
      infoModule.Increment();
   }

   public override String ToString()
   {
      return String.Format("{0} {1}", fName, lName);
   }
}
// The example displays the following output if missing1a.dll is renamed or removed:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'Person' threw an exception. ---> 
//       System.IO.FileNotFoundException: Could not load file or assembly 
//       'Missing1a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
//       or one of its dependencies. The system cannot find the file specified.
//       at Person..cctor()
//       --- End of inner exception stack trace ---
//       at Person..ctor(String fName, String lName)
//       at Example.Main()
System_CAPS_noteNote

In this example, a TypeInitializationException exception was thrown because an assembly could not be loaded. The exception can also be thrown if a static constructor attempts to open a data file, such as a configuration file, an XML file, or a file containing serialized data, that it cannot find.

You can set the default timeout value for a regular expression pattern matching operation on a per-application domain basis. The timeout is defined by a specifying a TimeSpan value for the "REGEX_DEFAULT_MATCH_TIMEOUT" property to the AppDomain.SetData method. The time interval must be a valid TimeSpan object that is greater than zero and less than approximately 24 days. If these requirements are not met, the attempt to set the default timeout value throws an ArgumentOutOfRangeException, which in turn is wrapped in a TypeInitializationException exception.

The following example shows the TypeInitializationException that is thrown when the value assigned to the "REGEX_DEFAULT_MATCH_TIMEOUT" property is invalid. To eliminate the exception, set the"REGEX_DEFAULT_MATCH_TIMEOUT" property to a TimeSpan value that is greater than zero and less than approximately 24 days.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      AppDomain domain = AppDomain.CurrentDomain;
      // Set a timeout interval of -2 seconds.
      domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2));

      Regex rgx = new Regex("[aeiouy]");
      Console.WriteLine("Regular expression pattern: {0}", rgx.ToString());
      Console.WriteLine("Timeout interval for this regex: {0} seconds",
                        rgx.MatchTimeout.TotalSeconds);
   }
}
// The example displays the following output:
//    Unhandled Exception: System.TypeInitializationException: 
//       The type initializer for 'System.Text.RegularExpressions.Regex' threw an exception. ---> 
//       System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
//       Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or 
//       object for specifying a default matching timeout for System.Text.RegularExpressions.Regex.
//       at System.Text.RegularExpressions.Regex.InitDefaultMatchTimeout()
//       at System.Text.RegularExpressions.Regex..cctor()
//       --- End of inner exception stack trace ---
//       at System.Text.RegularExpressions.Regex..ctor(String pattern)
//       at Example.Main()

If you attempt to instantiate a calendar but the runtime is unable to instantiate the CultureInfo object that corresponds to that calendar, it throws a TypeInitializationException exception. This exception can be thrown by the following calendar class constructors:

Since cultural data for these cultures should be available on all systems, you should rarely, if ever, encounter this exception.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft